HttpResponseMessage In WebAPI

HttpResponseMessage

A HttpResponseMessage allows us to work with the HTTP protocol (for example, with the headers property) and unifies our return type. In simple words, an HttpResponseMessage is a way of returning a message/data from your action.

The following is a quick glimpse of that.

// GetEmployee action
public HttpResponseMessage GetEmployee(int id)
{
    // Do Something

    HttpResponseMessage response = new HttpResponseMessage();
    // Customize your response here

    return response;
}

Why to return a HttpResponseMessage

Since we can return primitive types or complex types to the user, why HttpResponseMessage?

Let's create a simple get method that will return the Employee data for the id provided.

public Employee GetEmployee(int id)
{
    return EmployeeContext.Employees.FirstOrDefault(e => e.Id == id);
}

As you can see, the method above is fulfilling the requirement; it is returning the Employee details for the ID provided. But what if no such employee exists for the ID provided, it will return the null value with a successful response. Rather it would be more efficient if we return a 404 error, with a message like “Employee not found”.

Using HttpResponseMessage

Now let's modify our previous example to return a HttpResponseMessage for the Employee data for the ID provided.

// GetEmployee action
public HttpResponseMessage GetEmployee(int id)
{
    Employee emp = EmployeeContext.Employees.FirstOrDefault(e => e.Id == id);
    
    if (emp != null)
    {
        return Request.CreateResponse<Employee>(HttpStatusCode.OK, emp);
    }
    else
    {
        return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Employee Not Found");
    }
}

Now as you can see above, we have used a HttpResponseMessage as the return type for our get method that will now “CreateResponse” that will return the employee data and “HttpStatusCode.OK” if the employee exists for the Id provided and if no such employee exists then it will create a “CreateErrorResponse” and that will be returning the message “Employee Not Found” and “HttpStatusCode.NotFound”.

Using HttpResponseMessage with Try Catch

Now let's further modify the same example by adding try/catch blocks for exception handling.

// GetEmployee action
public HttpResponseMessage GetEmployee(int id)
{
    try
    {
        Employee emp = EmployeeContext.Employees.Where(e => e.Id == id).FirstOrDefault();

        if (emp != null)
        {
            return Request.CreateResponse<Employee>(HttpStatusCode.OK, emp);
        }
        else
        {
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Employee Not Found");
        }
    }
    catch (Exception ex)
    {
        // Log exception code goes here
        return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Error occurred while executing GetEmployee");
    }
}

This makes our code more robust by returning a custom error message with “HttpStatusCode.InternalServerError” if an exception occurs.

Summary

This article showed how to use HttpResponseMessage with raw HTTP responses for returning a message/data with “HttpStatusCode” from our WebApi action.


Similar Articles