How to return Http Status Code from ASP.NET Web API Controller ?

There are times when you might want to return the Http Status code from an action method of a ASP.NET Web Api Controller.

One of the simplest way of doing this is using the CreateResponse method of the HttpRequestMessage as shown below. The sample below demonstrates how to return the status code 304 and 200 based on the last modified date of the employee record.

How to return Http Status Code from ASP.NET Web API Controller ?

[ResponseType(typeof(Employee))]
public HttpResponseMessage GetACEmployee(HttpRequestMessage request, int empID, DateTime lastModified)
{
    var employee = new EmployeeContext.GetEmployees().First(p => p.Id == empID);
    if (employee.RecordLastModified <= lastModified)
    {
        return new HttpResponseMessage(HttpStatusCode.NotModified);
    }
    return request.CreateResponse(HttpStatusCode.OK, employee);
}

Leave Your Comment

Liked this content?. Please spread the word :)