2016-02-22

How to Return Status Code and Data from Web API

Lately I use ASP.NET WebAPI more than I do WCF WebServices (SOAP). Key reason is that I do a lot of mobile development where consummation of REST based services is native. It is easy to start working with Web API, but at some point you just want more than you see in demos.

In one of the projects I had to return data and also a custom status code. For this example, let say 304 – Not Modified. I had this piece of code:

public class TryController : ApiController
{
    public User GetUser(int userId, DateTime lastModifiedAtClient)
    {
        var user = new DataEntities().Users.First(p => p.Id == userId);
        if (user.LastModified <= lastModifiedAtClient)
        {
             throw new HttpResponseException(HttpStatusCode.NotModified);
        }
        return user;
    }
}

I felt that returning status code as a exception is not the right way to handle this scenario. Luckily I found answer on ASP.NET forum. The trick is to change the signature to HttpResponseMessage and use Request.CreateResponse:

[ResponseType(typeof(User))]
public HttpResponseMessage GetUser(HttpRequestMessage request, int userId, DateTime lastModifiedAtClient)
{
    var user = new DataEntities().Users.First(p => p.Id == userId);
    if (user.LastModified <= lastModifiedAtClient)
    {
         return new HttpResponseMessage(HttpStatusCode.NotModified);
    }
    return request.CreateResponse(HttpStatusCode.OK, user);
}

No comments:

Post a Comment