3
votes

WebAPI / REST allows you to send custom error messages together with a standard Status Code, i.e. 402 - Not found + your own message in the header / body.

This works great on ASP.NET 4.X, but with ASP.NET 5 RC 1 there's something amiss.

While my code to throw custom errors looks something like this:

throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Ambiguous) 
{ 
    Content = feedback, ReasonPhrase = reason }
);

The code returned (to Angular) isn't the code specified (300 in the example). On localhost / IIS Express i get 500 Internal Server Error and in production on Azure I get 404 Not Found.

Looking at the ASP.NET docs I see something that might be relevant:

If the server catches an exception before the headers have been sent it will send a 500 Internal Server Error response with no body.

https://docs.asp.net/en/latest/fundamentals/error-handling.html#server-exception-handling

So has anyone successfully returned status codes with custom (body) messages to client from ASP.NET 5 RC 1 WebAPI?

UPDATE:

This methodology seems to work better - but that doesn't answer why HttpResponseException doesn't work.

this.Response.StatusCode = (int)HttpStatusCode.BadRequest;
return this.HttpBadRequest(new { ex.Message });
1

1 Answers

0
votes

To answer your updated question, they removed that use of HttpResponseException because it encouraged the bad practice of using exceptions for flow control. See https://github.com/aspnet/Mvc/issues/4311.