Action Results in Web API

Introduction

This article explains the Action Results in ASP.NET Web API 2 and how Action Results returns the HTTP Response Message.

Action Results in Web API 2

There are four Action Results supported by ASP.NET Web API 2. They are:

  • HttpResponseMessage
  • IHttpActionResult
  • Void
  • Type of Entity that mean some other type

Note: IHttpActionResult is introduced in ASP.NET Web API 2 and the remaining are introduced in earlier versions of Web API.

HttpResponseMessage

HttpResponseMessage represents HTTP Response Message as per MSDN definition. If the return type of the action method is one of the Web API's action results, then the API converts the return value to a HTTP Response Message. This action result gives us more flexibility to create our own custom message using it's properties.

HttpResponseMessage has the following properties that will be useful to write custom response messages. (Image Courtesy: HttpResponseMessage Class).

HttpResponseMessage Class

Content

  1. [HttpGet]  
  2. public HttpResponseMessage GetStudent(int id)  
  3. {  
  4.    HttpResponseMessage response = new HttpResponseMessage();  
  5.    response.Content = new StringContent("This is HttpResponse's Content");  
  6.    return response;  
  7. }  
If we execute the preceding code, the content “This is HttpResponse's Content” will be added to the Response Body.

Similarly, we can set the StatusCode and Version of the HttpResponseMessage. And IsSuccessStatusCode returns the boolean value whether the returned status code is valid or not.

That means it checks whether the returned HttpStatusCode is valid or not.

In order to show how the HttpResponseMessage works, we have created an entity called Student.
  1. public class Student  
  2. {  
  3.    public int Id { getset; }  
  4.    public string FirstName { getset; }  
  5.    public string LastName { getset; }  
  6.    public string Location { getset; }  
  7. }  
Then, created a StudentController that is dervied from ApiController. The code as in the following.
  1. public class StudentController : ApiController  
  2. {  
  3.     List<Student> lstStudents = new List<Student>(){  
  4.     new Student(){Id=001,FirstName="Srinivas", LastName="Vadepally", Location="Hyderabad"},  
  5.     new Student(){Id=002,FirstName="Manoj", LastName="Kodepaka", Location="Banglore"},  
  6.     new Student(){Id=003,FirstName="Harish", LastName="Donthula", Location="Mumbai"},  
  7.     };  
  8.   
  9.     [HttpGet]  
  10.     public IEnumerable<Student> GetStudents()  
  11.     {  
  12.         return lstStudents;  
  13.     }  
  14.   
  15.     [HttpGet]  
  16.     public HttpResponseMessage GetStudent(int id)  
  17.     {  
  18.         HttpResponseMessage response = new HttpResponseMessage();  
  19.         response.Content = new StringContent("This is HttpResponse's Content");  
  20.         return response;  
  21.     }  
  22.       
  23. }  
Now, run the API by clicking on F5 and observe it in the Rest client. It will show “This is HttpResponse's Content” in the Response Body.

Response Body

Note: We have used RestClient on Mozilla Firefox.

The action method GetStudent(int id) return type is of HttpResponseMessage. As we added the content property to the response, the response body is showing the content. If we did not add anything nothing will be displayed and the status code will be 200 if the action is executed succesfully.

Another important thing is that we can pass the Entity along with the HttpResponseMessage. Web API internally converts the entity to a HTTP Response Message as we said in the beginning.
  1. [HttpGet]  
  2. public HttpResponseMessage GetStudent(int id)  
  3. {  
  4.    //HttpResponseMessage response = new HttpResponseMessage();  
  5.    //response.Content = new StringContent("This is HttpResponse's Content");  
  6.    HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, lstStudents.FirstOrDefault(s => s.Id == id));  
  7.    return response;  
  8. }  
According to the preceding code, the Student entity will be returned as HttpResponseMessage.

HttpResponseMessage

The ASP.NET Web API converts the Student entity into a HTTP Response Message. We can see the returned Student in XML representation.

Void

As we all know, void returns nothing. But in Web API the action result returns the Status Code 204 that is of No Content.
  1. [HttpGet]  
  2. public void GetStudent(int id)  
  3. {  
  4.    //HttpResponseMessage response = new HttpResponseMessage();  
  5.    //response.Content = new StringContent("This is HttpResponse's Content");  
  6.    //HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, //lstStudents.FirstOrDefault(s => s.Id == id));  
  7.    //return response;  
  8. }  
Void

IHttpActionResult

The IHttpActionResult action result was introduced in Web API 2. It also returns the HttpResponseMessage. But the code we write to send the HTTP Response Message will be reduced with this interface.
  1. [HttpGet]  
  2. public IHttpActionResult GetStudent(int id)  
  3. {  
  4.    return Ok();  
  5. }  
The preceding code returns the HTTP Response message as 200 Ok Status Code. As per IhttpActionResult's definition in the ASP.Net/Web API, it acts like a factory for HttpResponseMessage and comes with built-in responses, like Ok, BadRequest, NotFound, Unauthorized, Exception, Conflict and Redirect.

The IHttpActionResult interface contains a single method, ExecuteAsync.

IHttpActionResult

The async method of IhttpActionResult and ExecuteAsync will be called by the Web API to create a HttpResponseMessage and then convert the result into a HTTP response. At the end if we use HttpResponseMessage or IhttpActionResult, we will get the HTTP Response Message only. The benefit of IhttpActionResult is that we will have the built-in responses.

Type of Entity

If we use an entity as an action result in the Web API then we will get the HTTP Response Message as the Entity Type. The response is produced through the serialization of the entity.

Type of Entity

In the preceding method, the action result is of type Student Entity. The response of this method will be returned as a Student entity. That means the Student Object will be serialized and returned in the response body. The object will be returned in XML Data representation or in JSON as per the media formatter specified.

Summary

We discussed four types of Action Results in Web API 2 and how they return the HTTP Response Message. The important thing in the article is the built-in HTTP Response Messages from IhttpActionResults.


Similar Articles