I'm writing an MSMVC API to handle simple user registration. In the API I want to throw exceptions when the data passed to the controller is invalid.
public XmlResult RegisterByEmailAddress(UserModel model)
{
var errorResponse = new HttpResponseMessage(HttpStatusCode.BadRequest)
{
Content = new StringContent("Problem"),
ReasonPhrase = "Problem"
};
throw new HttpResponseException(errorResponse);
}
However regardless of what I set in the exception I only ever see a 500 error in the client response. I'm using Visual Studio 2012 and running the API in debug mode on the local IIS server.
The actual content of the response as seen in the Chrome Dev is :
Method : Get, Status : 500 Internal Server Error, Type text/html
Does anyone have any idea what the problem might be?
I think, based on your own answer, and some tests I just did, that your controller is inheriting from the wrong base class. If you posted the rest of the controller it might be easier to see.
All API controllers should inherit from ApiController
MyController : ApiController
OK, well after much trial and error the following works :
throw new HttpException((int)HttpStatusCode.BadRequest, "Invalid password provided to the Api");
This seems to go against the documentation which (I think) recommends throwing an HttpResponseException when developing an Api.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With