find and solve || findandsolve.com
Please wait.....

IHttpActionResult vs HttpResponseMessage

In my block I will try to set difference between IHttpActionResult and HttpResponseMessage and also advantages of using the IHttpActionResult.

First Consider using ASP.NET Core web API.It has the advantages over ASP.NET 4.x Web API given below. 

⦁  ASP.NET Core is an open-source and cross-platform framework for building modern, cloud-based web apps

   on Windows, macOS, and Linux.
⦁  Web API controllers and ASP.NET Core MVC controllers are unified.
⦁  Architected for testability.
⦁  Ability to develop and run on Windows, macOS, and Linux.
⦁  Open-source and community-focused.
⦁ Development workflows and integration of modern, client-side frameworks.
⦁  A cloud-ready, environment-based configuration system.
⦁  Built-in dependency injection.
⦁  A high-performance,lightweight, and modular HTTP request pipeline.
⦁  Ability to host on  [IIS](xref:host-and-deploy/iis/index, Kestrel,Nginx, Apache, HTTP.sys , and Docker.
⦁  Side-by-side versioning.
⦁  Tooling that simplifies modern web development.
 

A Web API controller action can return  like given below:

⦁ Void
 ⦁ HttpResponseMessage
 ⦁ IHttpActionResult
 ⦁ Some other type
 

Note: Return type    means Web API creates the response.

VOID

Return empty 204 (No Content).No return types.

For Example 

public class ValuesController : ApiController
 {
   public void PostMethod()
    {
    }
}

HTTP response:
HTTP/1.1 204 No Content
Server: Microsoft-IIS/8.0
Date: Mon, : Mon, 02 Dec 2020 02:13:26 GMT 

HttpResponseMessage:

 Web API converts the retrun value directly into an HTTP response message using HttpResponseMessage object to populate the response.

For Example

using System;
using System.Net;
usingSystem.Net.Http;
usingSystem.Net.Http.Headers;
usingSystem.Text;
usingMicrosoft.SqlServer.Management.Sdk.Sfc;
public class ValuesController : ApiController {     public HttpResponseMessage GetMethod()     {         HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, "value");         response.Content = new StringContent("Hi", Encoding.Unicode);         response.Headers.CacheControl = new CacheControlHeaderValue()         {             MaxAge = TimeSpan.FromMinutes(20)         };         return response;     } } 

Response:
HTTP/1.1 200 OK
Cache-Control: max-age=1200
Content-Length: 10
Content-Type: text/plain; charset=utf-16
Server: Microsoft-IIS/8.0
Date: Mon, 02 Dec 2020 08:53:35 GMT

Example of using HttpResponseMessage :

  public class ValuesController : ApiController
  {     public HttpResponseMessage GetMethod(int id)     {         var staff = dbContext.Staff.GetStaff(id);         if (staff == null)             return Request.CreateResponse(HttpStatusCode.NotFound);         // could also throw a HttpResponseException(HttpStatusCode.NotFound)         return Request.CreateResponse(HttpStatusCode.OK, staff);     } }

 

IHttpActionResult: 

Convert to an HTTP response message before Call ExecuteAsync to create an HttpResponseMessage.IHttpActionResult interface was introduced in Web API 2. 

Some advantages of using the IHttpActionResult interface:

⦁ Simplifies unit testing your controllers.
⦁ IHttpActionResult moves common logic for creating HTTP responses into separate classes.
⦁ IHttpActionResult  makes the intent of the controller action clearer, by hiding the low-level details of

   constructing the response.
⦁ It contains a single method, ExecuteAsync, which asynchronously creates an HttpResponseMessage instance. 

For Example


public class ValuesController : ApiController
{
    public IHttpActionResult GetStaff(int id)
    {
        var staff = dbContext.Staff.GetStaff(id);
        if (staff == null)             return NotFound();
        return Ok(staff);     } }  

 Predefined helper methods for IHttpActionResult are given below:

⦁ Ok : Returns an HTTP 200 (“OK”)

Redirect : Returns an HTTP 302 (“Found”)
NotFound : Returns an HTTP 404 (“Not Found”)
Unauthorized : Returns an HTTP 401 (“Unauthorized)
Conflict : Returns an HTTP 409 (“Conflict”)
BadRequest : Returns an HTTP 400 (“Bad Request”)

 Other type : return 200 (OK).Write the serialized return value into the response body; 
 

Sundar  Neupane

Sundar Neupane

I like working on projects with a team that cares about creating beautiful and usable interfaces.

Comments



Report Response