I been wondering this for a while now, is it better to always return HttpResponseMessage
web using asp.net mvc web api?
When I load up the default webapi project I see they don't use it in the sample controller
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
I thought the HttpResponseMessage
wraps everything around and makes it a good Http request. If this is correct what is the benefit of not just using it?
A HttpResponseMessage allows us to work with the HTTP protocol (for example, with the headers property) and unifies our return type. In simple words an HttpResponseMessage is a way of returning a message/data from your action.
11) What is the biggest disadvantage of “Other Return Types” in Web API? The biggest disadvantage of this approach is that you cannot directly return an error code like 404 error.
By default Web API returns result in XML format.
I always return HttpResponseMessage. The point of Web API is to be able to expose an HTTP api. Pretending that you are returning an object and then relying on the framework pipeline to convert the object to a HTTPResponseMessage is just obscuring the intent IMO.
I am confident that if you pay the extra up front cost of creating the HttpResponseMessage yourself, you will understand better how Web API actually works. You will run into less problems because you are more likely to avoid Web API doing something you were not expecting. You will more likely take advantage of HTTP capabilities because the headers are right there for you to access.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With