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.
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);
}
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.

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.







Yogi SPosted Mar 31, 2017, 1:28 PM
Great article, i was looking for the OK thing and when i got your blog. Helped me to learn a new thing today.