Amey Deshpande
Amey Deshpande

Reputation: 61

return type in webAPI call


What is the significance of using IHttpActionResult as a return type in ASP.NET WebAPI method call.
As this is a interface how can we return a result in the form of interface ?
can someone explain the concept behind this?

Thanks in Advance !!

Upvotes: 1

Views: 7381

Answers (1)

Masoud Andalibi
Masoud Andalibi

Reputation: 3228

Based on the Microsoft ASP.NET Documentation,

The IHttpActionResult interface was introducted in Web API 2. Essentially, it defines an HttpResponseMessage factory. Here are some advantages of using the IHttpActionResult interface:

  • Simplifies unit testing your controllers.
  • Moves common logic for creating HTTP responses into separate classes.
  • Makes the intent of the controller action clearer, by hiding the low-level details of constructing the response.

IHttpActionResult contains a single method, ExecuteAsync, which asynchronously creates an HttpResponseMessage instance.

public interface IHttpActionResult
{
    Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken);
} 

If a controller action returns an IHttpActionResult, Web API calls the ExecuteAsync method to create an HttpResponseMessage. Then it converts the HttpResponseMessage into an HTTP response message.

Here is a simple implementaton of IHttpActionResult that creates a plain text response:

public class TextResult : IHttpActionResult
{
    string _value;
    HttpRequestMessage _request;

    public TextResult(string value, HttpRequestMessage request)
    {
        _value = value;
        _request = request;
    }
    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var response = new HttpResponseMessage()
        {
            Content = new StringContent(_value),
            RequestMessage = _request
        };
        return Task.FromResult(response);
    }
}

Another Sample in Controller:

public class ValuesController : ApiController
{
    public IHttpActionResult Get()
    {
        return new TextResult("hello", Request);
    }
}

And Its Respond:

HTTP/1.1 200 OK Content-Length: 5 Content-Type: text/plain; charset=utf-8 Server: Microsoft-IIS/8.0 Date: Mon, 27 Jan 2014 08:53:35 GMT

hello

I hope this helps. Good luck.

Upvotes: 1

Related Questions