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:
-
- public HttpResponseMessage GetEmployee(int id)
- {
-
- }
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.Where(e => e.Id == id).FirstOrDefault();
- }
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.
-
- public HttpResponseMessage GetEmployee(int id)
- {
- 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");
- }
-
- }
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.
-
- 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)
- {
-
- return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Error occured 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.