ASP.NET Web API 2 action method return types

A Web API 2 action method return types can be any of the following :

  • Void
  • HttpResponseMessage
  • IHttpActionResult
  • Other type or Complex type

A Web API 2 action method return types can be any of the following
 

Void

When an ASP.NET Web API return type is void, it will return an empty HTTP response.

In the following example a web API with void return:

Example

1
2
3
4
5
6
7
8
<code>public class SampleController : ApiController
{
  public void Post()
   {
 
   }
}
</code>
<code>public class SampleController : ApiController
{
  public void Post()
   {

   }
}
</code>

Note: We are using fiddler to call Web API, it is a free web debugging proxy which logs all HTTP(s) traffic between your computer and the Internet

Result

Calling sample web API in fiddler

Web API 2 action method void return

It is returning status code 204 No Content (an empty HTTP response)

Web API 2 action method void return status code 204 No Content (an empty HTTP response)


 

HttpResponseMessage

  • When Web API return type is HttpResponseMessage, Web API converts the return value directly into an HTTP response message.
  • We can set the status code, content as per our requirement.

 

In the following example a web API with HttpResponseMessage return:

Example

1
2
3
4
5
6
<code>public HttpResponseMessage Get()
{
    HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, "value1");            
    return response;
}
</code>
<code>public HttpResponseMessage Get()
{
    HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, "value1");            
    return response;
}
</code>

Result

Calling sample Web API with HTTP GET request

Web API 2 action method HttpResponseMessage return

In Response, It is returning status code 200 OK and Content

Web API 2 action method void return status code 204 No Content (an empty HTTP response)

Note:Web API serialized model into the response body based on request header formatter

In the following example a web API return HttpResponseMessage with list of Countries in response body:

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<code>public HttpResponseMessage Get()
{
   // list of Countries
   List<Country> Countries = new List<Country>();
    Country country = new Country();
    country.ID = 1;
    country.CountryName = "USA";
    country.Capital = "Washington";
    Countries.Add(country);
 
    //Countries to the response body.             
    HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, Countries);            
    return response;
}
</code>
<code>public HttpResponseMessage Get()
{
   // list of Countries
   List<Country> Countries = new List<Country>();
    Country country = new Country();
    country.ID = 1;
    country.CountryName = "USA";
    country.Capital = "Washington";
    Countries.Add(country);

    //Countries to the response body.             
    HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, Countries);            
    return response;
}
</code>

Result

In Response, It is returning status code 200 OK and Content

Web API 2 action method HttpResponseMessage return


 

IHttpActionResult

IHttpActionResult is introduced in Web API 2, IHttpActionResult interface acts like a factory for HttpResponseMessage.

 

There are some advantages of using the IHttpActionResult over HttpResponseMessage
  • The code is cleaner and easier to read
  • Unit testing for controller action methods become easy
  • It comes with custom built in responses
    • Ok
    • NotFound
    • Exception
    • Unauthorized
    • BadRequest
    • Conflict
    • Redirect
In the following example a web API return IHttpActionResult with list of Countries in response body:

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<code>public IHttpActionResult Get(int id)
{
   // list of Countries
   List<Country> Countries = new List<Country>();
    Country country = new Country();
    country.ID = 1;
    country.CountryName = "USA";
    country.Capital = "Washington";
    Countries.Add(country);
 
    //finding country based on provided id
    var result = Countries.FirstOrDefault(x=> x.ID ==id);
    if (result == null)
    {
        //create a 404 (Not Found) response
        return NotFound();                
    }
    else
    {
        //creates a 200 (OK) response that contains the country
        return Ok(result);
    }
}
</code>
<code>public IHttpActionResult Get(int id)
{
   // list of Countries
   List<Country> Countries = new List<Country>();
    Country country = new Country();
    country.ID = 1;
    country.CountryName = "USA";
    country.Capital = "Washington";
    Countries.Add(country);

    //finding country based on provided id
    var result = Countries.FirstOrDefault(x=> x.ID ==id);
    if (result == null)
    {
        //create a 404 (Not Found) response
        return NotFound();                
    }
    else
    {
        //creates a 200 (OK) response that contains the country
        return Ok(result);
    }
}
</code>

Result

Calling sample web API with HTTP GET request and id

Web API 2 action method HttpResponseMessage return

In Response, It is returning status code 200 OK and Content

Web API 2 action method HttpResponseMessage return

Calling sample web API with HTTP GET request and id(which is not exist)

Web API 2 action method HttpResponseMessage return

In Response, It is returning status code 404 Not Found

Web API 2 action method HttpResponseMessage return


 

Other type or Complex type

  • A Web API can return other or custom complex type
  • Web API serialize value and return it into the response body
  • The response status code 200 OK
  • But in this approach we cannot directly return an error code, still we can throw an HttpResponseException for error codes

In the following example a web API with Complex return type:

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<code>public class CountryController : ApiController
{
    public IEnumerable<Country> Get()
    {
        List<Country> Countries = new List<Country>();
        Country country = new Country();
        country.ID = 1;
        country.CountryName = "USA";
        country.Capital = "Washington";
        Countries.Add(country);
        return Countries;
    }
}
</code>
<code>public class CountryController : ApiController
{
    public IEnumerable<Country> Get()
    {
        List<Country> Countries = new List<Country>();
        Country country = new Country();
        country.ID = 1;
        country.CountryName = "USA";
        country.Capital = "Washington";
        Countries.Add(country);
        return Countries;
    }
}
</code>

Result

Calling Country web API with HTTP GET request

Web API 2 action method Complex return type

In Response, It is returning status code 200 OK and Content

Web API 2 action method void return status code 204 No Content (an empty HTTP response)

Source: http://www.tutorialplus.net/

Share the joy
  •  
  •  
  •  

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.