Reputation: 11412
In ASP.NET WebApi 2, what is the difference between the following:
public <IHttpActionResult> GetItem(Guid id)
{
// ... code ..., Item result = ....
return result;
}
public <IHttpActionResult> GetItem(Guid id)
{
// ... code ..., Item result = ....
return Json(result);
}
public <IHttpActionResult> GetItem(Guid id)
{
// ... code ..., Item result = ....
return Ok(result);
}
Upvotes: 18
Views: 11901
Reputation: 37
Just an addition to previous explanations:
The return types for your fuctions are: IHttpActionResult
Therefore the expectation is for the method to return a IHttpActionResult
which is an interface for HttpResponseMessage
. The HttpResponseMessage
has useful properties such as Headers, Content, and Status code.
Therefore, Ok(result)
returns a HttpResponseMessage
with Ok
status code and the contents, which in this case is the result. Meanwhile, Json(result)
converts the object to json format, aka serialization, and that gets placed as the content in the HttpResponseMessage
.
The best thing about a web api with ASP.NET is that it creates simple ways to pass the Http Responses through abstraction. The worst thing, is it takes a bit of understanding before actually using the relatively simple methods.
Here is more info about serilization and json
Here is more about info about IHttpActionResult
Upvotes: 1
Reputation: 37540
This code returning result
won't compile, as result
doesn't implement IHttpActionResult
...
public <IHttpActionResult> GetItem(Guid id)
{
// ... code ..., Item result = ....
return result;
}
Returning Json()
always returns HTTP 200 and the result in JSON format, no matter what format is in the Accept header of the incoming request.
public <IHttpActionResult> GetItem(Guid id)
{
// ... code ..., Item result = ....
return Json(result);
}
Returning Ok()
returns HTTP 200, but the result will be formatted based on what was specified in the Accept request header.
public <IHttpActionResult> GetItem(Guid id)
{
// ... code ..., Item result = ....
return Ok(result);
}
Upvotes: 32