true

Find the best tutors and institutes for .NET MVC

Find Best .NET MVC

Please select a Category.

Please select a Locality.

No matching category found.

No matching Locality found.

Outside India?

Search for topics

ASP.NET Web API 2 action method return types

Sachin Kumar
04/07/2017 0 0

Here, in this article we will learn 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

public class SampleController : ApiController
{
  public void Post()
   {
            
   }
}

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

public HttpResponseMessage Get()
{
    HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, "value1");            
    return response;
}


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

public HttpResponseMessage Get()
{
   // list of Countries
   List Countries = new List();
    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;
}


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

public IHttpActionResult Get(int id)
{
   // list of Countries
   List Countries = new List();
    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);
    }
}





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

public class CountryController : ApiController
{
    public IEnumerable Get()
    {
        List Countries = new List();
        Country country = new Country();
        country.ID = 1;
        country.CountryName = "USA";
        country.Capital = "Washington";
        Countries.Add(country);
        return Countries;
    }
}

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) 
0 Dislike
Follow 0

Please Enter a comment

Submit

Other Lessons for You

Steps to fill drop-down value from database to view page in ASP.Net MVC Application
In simple few steps you can fill the dynamic data from database to HTML page in MVC Application Write connection string in web config file Create table related getter setter in model Fetch data...

Jaffrena M. | 11 Jun

0 0
0

Multi-core CPU utilization using Task Parallel Library in c#
Nowadays, we are using multiple core systems. We must write our .NET applications in such a way that we must utilise the complete computing power of the machine. The parallel task library(TPL) allows...

Ketan Agnihotri | 12 Jan

0 0
0

What is the need for Restful Service in MVC Core?
EXPLANATIONRestful service makes access to client information send to the server by JSON request that reduces several round trips from the server and hence optimises the speed. HTML framework works the...

Suprio Dutta | 15/12/2018

0 0
0

CLR [ Common Language Runtime ] and it's properties
CLR is one of the components of the .NET framework which provides an environment to execute the .NET code or the managed code. , CLR helps in converting the MSIL/CIL code into native code and running...

Raga Deepthi G. | 05/11/2018

0 0
0

Garbage collector [ GC ] in .NET framework
Garbage collector is responsible for the "automatic memory management - AMM" in .NET framework. Garbage collector is one of the properties of .NET framework components CLR . Why there is a need of "Memory...

Raga Deepthi G. | 31/10/2018

1 0
0

Find Best .NET MVC ?

Find Now »

UrbanPro.com is India's largest network of most trusted tutors and institutes. Over 25 lakh students rely on UrbanPro.com, to fulfill their learning requirements across 1,000+ categories. Using UrbanPro.com, parents, and students can compare multiple Tutors and Institutes and choose the one that best suits their requirements. More than 6.5 lakh verified Tutors and Institutes are helping millions of students every day and growing their tutoring business on UrbanPro.com. Whether you are looking for a tutor to learn mathematics, a German language trainer to brush up your German language skills or an institute to upgrade your IT skills, we have got the best selection of Tutors and Training Institutes for you. Read more