ASP.NET Tutorial – HttpResponseMessage In WebAPI

5 (100%) 1 vote

BestASPNETHostingReview.com | Best and cheap ASP.NET Hosting. 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:

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.

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 success response. Rather it would be more efficient if we return 404 error, with 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.

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.

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.