6

I'm trying to return appropriate Http codes and responses from my application but I am struggling. It seems that there are 2 ways to return specific http responses.

The way I want to deal with it is by throwing a HttpResponseException:

public Information Get(int apiKey)
{
    if (!_users.Authenticate(apiKey))
    {
        var response = new HttpResponseMessage();
        response.StatusCode = (HttpStatusCode)401;
        response.ReasonPhrase = "ApiKey invalid";

        throw new HttpResponseException(response);
    }

    return _info.Get();
}

However, when I do this the response I see is just an empty 200 response!

It also seems that you can also change the signature of your action method to return a HttpResponseMessage like this:

public HttpResponseMessage Get()
{
    if (!_users.Authenticate(apiKey))
    {
        return Request.CreateResponse((HttpStatusCode) 401, "ApiKey invalid");
    }

    return Request.CreateResponse((HttpStatusCode) 200, _info.Get());
}

I really don't want to do this if I can help it, I would much rather have my return type as the object I am trying to retrieve rather than wrapping it every time in a HttpResponseMessage.

Is there a reason why the first method is returning an empty 200 rather than the 401 with the message as I want it to?

jcvandan
  • 14,124
  • 18
  • 66
  • 103

2 Answers2

5

Two possible solutions;

First. Make sure your IIS is configured to let errors pass through

<configuration>
  <system.webServer>
    <httpErrors existingResponse="PassThrough" />
  </system.webServer>
</configuration>

Second. I am not entirely sure, but ASP.NET Web API may require you to develop a custom ActionFilter to properly translate Exceptions to result types. This is the way I personally do error handling in Web API:

  1. Allow any type of Exception to be thrown in Web API, just like you would do in any other .NET application
  2. Write a custom ActionFilter that catches Exceptions and translates them to the appropriate format. For instance, I serialize all Exceptions in a custom JSON format. On the client-side, I have some custom AJAX trickery that can handle errors (such as validation exceptions) based on this format.
Martin Devillers
  • 17,293
  • 5
  • 46
  • 88
  • cheers for that - I did end up using a filter to deal with exceptions in the end thanks to you pointing me towards that msdn article – jcvandan Sep 04 '12 at 19:23
1

Check IncludeErrorDetailPolicy setting on HttpConfiguration. By default, the policy is to show error details while accessing Web API locally.

Kiran
  • 56,921
  • 15
  • 176
  • 161