A New Way to Send Response Using IHttpActionResult

Hi all, I hope everyone is fine, me too. I am being amazed day by day by seeing new features and improvements to MVC from Microsoft. If you have had hands-on experience with MVC and the Web API then you are very familiar with HTTP responses from the Web API.

If we remember the HTTP response creation of Web API 1.0 we used to use write 3 to 4 lines of code to create one full fledge HTTP response by setting the status code and media type with an appropriate message. The style is something like this.

  1. var response = new HttpResponseMessage(HttpStatusCode.Unauthorized);  
  2. var tsc = new TaskCompletionSource<HttpResponseMessage>();  
  3. tsc.SetResult(response);  
  4. return tsc.Task;  
This code snippet will return one Unauthorized HTTP response (haha.. not an unauthorized response, but HTTP response of unauthorized type) asynchronously. Now, if we want to change the response type then obviously we must change the status code.

Fine and simple but it is simpler in the Web API 2. We can create the same kind of response with a single line of code.

Here you will see how the ASP.NET Web API converts the return value from a controller into an HTTP response message.

Please note that the feature is available in Web API 2.0, so please ensure that your application is updated to 2.0 versions before trying the following code. We know that a Web API controller action can return any one of the following.
  • Void
  • HttpResponseMessage
  • IHttpActionResult (new in Web API 2.0)
  • Some other data type

Now in today's article we will see the third point with an example. To use IHttpResult in your application, you must include “System.WebHttp” and provide a reference of the “system.Web.Http” assembly.

The interface IHttpActionResult contains one any only one method called “ExecuteAsync”. Here is the definition of the interface:

  1. public interface IHttpActionResult  
  2. {  
  3.    Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken);  
  4. }  
Fine, now let's see how to return a HTTP Response from the controller with a single line of code using the interface. Have a look at the following example.
  1. public class personController : ApiController  
  2. {  
  3.    public IHttpActionResult Get()  
  4.    {  
  5.       return Ok();  
  6.    }  
  7.   
  8. }  
Here I have implemented a small empty person controller and defined a Get() within it. The Get() method is again empty and returning only Ok and this is the key point of the example. We know that Ok or success is one status type of HTTP and it's code is 200.

So, when we are returning Ok from a controller/action then the Web API runtime engine is transfers the Ok to a full fledge response message by setting the status code 200 with it. Let's see how it works practically. We will call the action from the client and we will check whether or not it returns an Ok response message. Here is the output from Fiddler.
 


And we are seeing that the status code is 200 and type is OK. So, now just think how simple it is to create a HTTP response from Web API 2.0.

Ok, you may think, how to embed some value with the HTTP response message? Fine, the next example is for you.

  1. public class personController : ApiController  
  2. {  
  3.    public IHttpActionResult Get()  
  4.    {  
  5.       return Ok<string> ("I am send by HTTP resonse");  
  6.    }  
  7.   
  8. }  
We are just returning string a in the message body and the output in Fiddler is something like this.
 


Please look that, the response string is coming as a body of HTTP response. Not only string, we can send any complex type of custom data type as a body of the HTTP response message. In the next example we will try to send a list of strings in the body of the response message with an Ok status. Here is our modified code.
  1. public IHttpActionResult Get()  
  2. {  
  3.     List<string> names = new List<string> {   
  4.        "Sourav",  
  5.        "Ram"  
  6.     };  
  7.     return Ok<List<string>> (names);  
  8. }  
And the output is in JSON format.



Fine, so we have seen how easy it is to create an Ok HTTP response message in the Web API, just by a single line of code. Not only an Ok message, but we can also return any type of valid HTTP response, let's see a few of them.

Not Found
  1. public IHttpActionResult Get()  
  2. {  
  3.    return NotFound();  
  4. }  
Like Ok() , we can return NotFound() , it will return a 404 status code as in the following screen.



Bad Request
  1. public IHttpActionResult Get()  
  2. {  
  3.    return BadRequest();  
  4. }  
We know the status code for BadRequest is 400 and once we call the method, we will get the status.



Unauthorized

In the same way, we can return an unauthorized status code, here is sample code.
  1. public IHttpActionResult Get()  
  2. {  
  3.    return Unauthorized();  
  4. }  


Created


The status code for the Created status is 201 and generally the status is returned when the Post() operation is performed successfully. Created takes two parameters, one is the “uri” and the other is content.



Conclusion

In this article, we have discussed how to send a HTTP response message with a minimal amount of code. I Hope you have understood this and like it. Happy learning.


Similar Articles