Last post Mar 10, 2016 08:43 AM by xdzgor
Mar 09, 2016 08:13 AM|xdzgor|LINK
Hi - sometimes I see web-api methods which return a custom object:
public CustomerInfo GetInformation() ...
Sometimes I see a return value like IHttpActionResult:
public IHttpActionResult GetStories()
public HttpResponseMessage DownloadIdentifier(string documentIdentifier, string documentType) ...
What are the pros-and-cons of each type of return?
The last two actually just seem to wrap other custom classes in the code (which I've seen), so why not just return those classes?
Mar 09, 2016 08:47 AM|Yohann Lu|LINK
As far as I know, WebAPI basically return 4 type of object: void, HttpResponseMessage, IHttpActionResult, and other strong types. First version WebAPI returns HttpResponseMessage which is pretty straight forward HTTP response message.
IHttpActionResult was introduced by WebAPI 2 which is a kind of wrap of HttpResponseMessage. It contains ExecuteAsync methods to create an HttpResponseMessage. It simplifies unit testing of your controller. Another advantage of using IHttpActionResult as
return type is that it makes ASP.NET Web API action method similar to MVC. You can return any action result without getting caught in media formatters.
Other return type is kind of strong typed classes serialized by the Web API using a media formatter into the response body. The drawback was you cannot directly return an error code, such as 404. All you can do is throwing an HttpResponseException error.
Mar 10, 2016 08:43 AM|xdzgor|LINK
Nice explanation, thanks.