user1615362
user1615362

Reputation: 3817

How to change the response code when not using HttpResponseMessage?

I have this example of ASP.NET Web Api controller:

    public Mea Get(Int32 id)
    {
        try
        {
            return Meas.GetById(id) ?? new Mea(-1, 0D, 0D);
        }
        catch (Exception)
        {
            return new Mea(-1, 0D, 0D);
        }
    }

I want to be able to return a different response code if the GetById returns null or in the catch exception. All the examples that I see use HttpResponseMessage where you can add the response code. My question is how to change the response code when not using HttpResponseMessage, like in the above example?

Upvotes: 0

Views: 570

Answers (2)

wizzardz
wizzardz

Reputation: 5874

Well if you want to have different response code to be return from your function then you will have to wrap it in in a HttpResponseMessage.

Your function will always return an status code "200". Even if you return a bare object the framework pipeline will convert it to a HttpResponseMessage with default status code HttpStatusCode.OK, so better you do it by yourself.

What I would suggest is do not return bare objects/values from your API function. Always wrap the values in a HttpResponseMessage and then return a response message from your function.Basically by wrapping it in the HttpResponseMessage you can have proper status code in client side. Returning HttpResponseMessage is always the best practice.

So please change your function like this

public HttpResponseMessage Get(Int32 id)
{
    try
    {
     // on successful execution
      return this.Request.CreateResponse(HttpStatusCode.OK, Meas.GetById(id) ?? new Mea(-1, 0D, 0D));
    }
    catch (Exception)
    {
      return this.Request.CreateResponse(HttpStatusCode.InternalServerError, Mea(-1, 0D, 0D));
    }
}

in the case of an error you can also throw an HttpResponseException

Upvotes: 1

metalheart
metalheart

Reputation: 3809

You can throw a System.Web.Http.HttpResponseException, specifying an HTTP status code and/or optionally a whole HttpResponseMessage to be returned to the client.

Upvotes: 0

Related Questions