Throwing HttpResponseException from WebApi controller when using Owin self host
You can put a breakpoint on the exception in OnException()
and view the context.Exception.Response, and see the "Reason Phrase" for an explanation.
You can also do this to access it via code:
((System.Web.Http.HttpResponseException)context.Exception).Response.ReasonPhrase
For me it was
Unsupported Media Type
Which other people have already mentioned can happen when you do a text request, because text requests are not handled by default. If you do want to allow text, maybe look at: how to post plain text to ASP.NET Web API endpoint?
I experienced this while I was using postman to test the web api and the request type was set to plain text instead of application/json.
I don't think the problem is in throwing HttpResponseException
. If you look at the stack trace you posted, the problem appears to be in the call to MoveNext()
. This is an internal C# representation of the yield
statements you have.
I could be wrong, but the easiest way to verify this is to put a breakpoint on the first yield statement and see if it hits it. My guess is that it will, i.e. it won't throw a HttpResponseException
. Also, just change your code temporarily to always throw an HttpResponseException
and see how it handles it.
I'm currently working on a project that's self-hosted using OWIN and I can throw HttpResponseException
s without any issues.
On a related note, you may want to investigate global exception handling. I found it very useful to concentrate all my exception handling in one place. Note that HttpResponseException
is a special case and is not handled by the global exception handler.
For me, I was missing content-type in my api header. After adding the content-type as application/json resolved this issue for me. Might help others with this.