Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net webapi controller, return typed entity or HttpResponseMessage

i would like to know what is the benefit of using HttpResponseMessage as the return type in my ApiController ? compare to returning the typed entity or collection directly.

we were trying to decided on a practice to keep things consistent for the project we are working on.

like image 911
Eatdoku Avatar asked Apr 09 '13 19:04

Eatdoku


1 Answers

Returning HttpResponseMessage is useful when you are trying to use your controller layer as the translation between the HTTP protocol and your internal .Net services. It allows direct control over the HTTP payload and headers. It makes it easy to return 202, 204, 304, 303 responses. It makes it easy to set caching headers. You have explicit control over the media type of the response.

By returning an object you effectively adding a "do nothing" layer to your architecture. Consider....

public Foo Get(int id) {
   return _fooRepository.GetFoo(id)
}

What is the purpose of this method? What value does it add? At least in MVC land, the controller had the role of matching the model and the view.

When you return objects from an APIController you have to impact the HTTPResponseMessage indirectly using a set of abstractions that are specific to Web API/MVC and have no corresponding concept in the HTTP world. Formatters, ActionFilters, ModelBinders, HttpResponseException are all infrastructure designed to allow the framework to process your HTTP request and response messages behind the scenes.

Returning HttpResponseMessage directly requires that your controller method does the work necessary to return the desired HTTP message.

I don't believe that it adds any complexity to your application, it just makes what is happening visible.

It comes down to whether you want to use Web API as an "object remoting over HTTP" framework (in which case I would also take a look at ServiceStack) or whether you want to take advantage of HTTP as an application protocol.

like image 133
Darrel Miller Avatar answered Oct 25 '22 03:10

Darrel Miller