简体   繁体   中英

.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 ... ?

See this and this SO questions.

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

HttpResponseMessage allows you to work with HTTP protocol (eg, 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM