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);
}
有帮助吗?

解决方案

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);
}

其他提示

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top