Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throwing an HttpResponseException always results in a StatusCode: 500 response in the client

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?

like image 955
Richard Adams Avatar asked Oct 20 '25 12:10

Richard Adams


2 Answers

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
like image 127
Simon C Avatar answered Oct 22 '25 02:10

Simon C


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.

like image 40
Richard Adams Avatar answered Oct 22 '25 03:10

Richard Adams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!