chobo2
chobo2

Reputation: 85845

Is It Better To Always Return HttpResponseMessage in Web Api?

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?

Upvotes: 17

Views: 7774

Answers (2)

riadh gomri
riadh gomri

Reputation: 869

For separating concerns why not having a service layer (strong typed methods in a class library) and a webservice layer (ASP.NET WEB API ).
The service layer can easily be consumed by Winform, WPF, Console and test projects with no Http dependency and also can be exposed as webservice by ASPNET WebAPi for example for mobile application and/or javascript .
The webservice Layer concern is to expose the service layer with http concerns (headers, content type, http status..) so you can return HttpResponseMessage.
This also make controller really thin and you can inject the service with DI

Upvotes: 3

Darrel Miller
Darrel Miller

Reputation: 142222

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.

Upvotes: 18

Related Questions