Reputation: 4484
I've seen viewmodels returned from webapi methods in two different ways. What's the difference and which is standard?
[HttpGet]
public List<UserViewModel> Get()
{
//stuff here
return usersViewModels;
}
[HttpGet]
public HttpResponseMessage Get()
{
//stuff here
return Request.CreateResponse(HttpStatusCode.OK, usersViewModels);
}
Upvotes: 1
Views: 488
Reputation: 11396
I personally use HttpResponseMessage
whenever actual manipulation of Status Codes (error handling, and the such) or headers is necessary. If not, I return common objects. I find it more legible and easier to assert through Unit Tests.
This mostly applies when you implement error handling as a cross-cutting concern (through aspects for example) and your Controller code doesn't actually handle that manually. In that case it's safe to return other objects.
Upvotes: 1
Reputation: 4860
Basically both will return the same data, but working with the HttpResponseMessage
is more flexible and provides you the opportunity to change values of the returned Http response.
For example, the first method returns the data with a fixed HttpStatusCode.OK (200) if not exception is raised. In the second method you can choose the HttpStatusCode that you want to return. Also will be able to change HTTP Headers like ContentType, ContentDisposition, etc.
Check out this concise and helpful article about this topic http://soabubblog.wordpress.com/2013/07/07/web-api-httpresponsemessage/
Also this one from the official asp.net website explains the different types of results that a Web API controller can return, indicating the advantages of each one http://www.asp.net/web-api/overview/web-api-routing-and-actions/action-results
Upvotes: 4