A New Way to Send Response Using IHttpActionResult

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. 

var response = new HttpResponseMessage(HttpStatusCode.Unauthorized);    

var tsc = new TaskCompletionSource<HttpResponseMessage>();    

tsc.SetResult(response);    

return tsc.Task;   

This code snippet will return one Unauthorized HTTP response (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: 

public interface IHttpActionResult

{

    Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken);

}  
 

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. 
 

public class personController : ApiController

{

    public IHttpActionResult Get()

    {

        return Ok();

    }

}

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. 

public class personController : ApiController

{

    public IHttpActionResult Get()

    {

        return Ok<string>("I am send by HTTP resonse");

    }

}

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.

public IHttpActionResult Get()    

{    

    List<string> names = new List<string> {     

       "Sourav",    

       "Ram"    

    };    

    return Ok<List<string>> (names);    

}   
 

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
 

public IHttpActionResult Get()    

{    

   return NotFound();    

}   

Like Ok() , we can return NotFound() , it will return a 404 status code as in the following screen.




Bad Request
 

public IHttpActionResult Get()    

{    

   return BadRequest();    


 

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. 
 

public IHttpActionResult Get()    

{    

   return Unauthorized();    


 



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.
Next Recommended Reading Send Sms from ASP.NET using Full On Sms