Question

I am having trouble returning the correct HTTP error code for a "not found" in my WCF Web API code. Here is my api method ...

    [WebInvoke(Method = "GET", UriTemplate = "{id}")]
    [RequireAuthorisation]
    public Customer GetCustomer(int id)
    {
        var customer = Repository.Find(id);
        if (customer == null)
        {
            throw new HttpResponseException(HttpStatusCode.NotFound);
        }
        return customer;
    }

I also have a logging handler ...

    protected override bool OnTryProvideResponse(Exception exception, ref HttpResponseMessage message)
    {
        if (exception != null)
        {
            var msg = "Request failed.";
            _logger.Error(exception, msg);
        }

        message = new HttpResponseMessage
                      {
                          StatusCode = HttpStatusCode.InternalServerError
                      };

        return true;
    }

What is happening is I am getting the following exception ...

HttpResponseException

"The response message returned by the Response property of this exception should be immediately returned to the client.  No further handling of the request message is required."

... which my logging handler picks up and changes the response status code to a 500.

So, based on reading a few blog posts and answers on SO, I changed to this ...

        if (customer == null)
        {
            WebOperationContext.Current.OutgoingResponse.SetStatusAsNotFound();
            return null;
        }

... but this now give me a 200. Which is clearly wrong.

So, what is the right way to do this? It seems as if the throwing of the HttpResponseException doesn't work and the code after gets executed.

Was it helpful?

Solution

The code snippet for your error handler is always changing the response message to 500 no matter what as you are explicitly setting the status always to 500.

It sounds like what you are trying to do is return a 500 ONLY if it is an application error. If that is the case you should check if the error exception is an HttpResponseException and just return rather than overriding.

As to WebOperationContext, don't use it at all with Web Api as it is basically no-op.

Hope this helps Glenn

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top