Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Web API HttpResponseMessage Pattern?

So I've seen the Web API 2 Controllers return HttpResponse and the actual object. Example:

 public HttpResponseMessage Get(string id)
    {
        var app = apps.Single(c => c.Id == id);

        return new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new ObjectContent<object>(app,
                Configuration.Formatters.JsonFormatter)
        };
    }

or

 public Application Get(string id)
    {
        return apps.Single(c => c.Id == id);
    }

My question which is the 'right' way? #2 is much shorter but is it better to do #1 or does #2 do #1 automatically ... ?

like image 547
amcdnl Avatar asked Nov 19 '13 22:11

amcdnl


1 Answers

See this and this SO questions.

The response will be the same (HttpResponseMessage) in both cases.

HttpResponseMessage allows you to work with HTTP protocol (e.g., via Headers property) and unifies your return type.

Returning CLR types can be more readable, but you loose flexibility to return different types with different status codes unless you use dynamic or object which defeats the purpose of returning a specific type.

Personally, I prefer to use IHttpActionResult (added in v2) and to specify a ResponseTypeAttribute on controller actions for the expected return type to improve readability.

[HttpGet]
[ResponseType(typeof(Portfolio))]
public IHttpActionResult GetPortfolio([FromUri] long id)
{
    // get portfolio

    return Ok(portfolio);
}

You can easily manipulate response messages (in a RESTful way) using default IHttpActionResult implementations (see OkResult above). Avoiding constructing HttpResponseMessage yourself also keeps code clean. Here is an official article on IHttpActionResult and here is an interesting SO conversation on HttpResponseMessage vs IHttpActionResult.

like image 101
Nikolai Samteladze Avatar answered Nov 15 '22 09:11

Nikolai Samteladze