IHttpActionResult返回项目,Json(项目)和Ok(项目)之间的区别

Ada*_*abo 11 asp.net asp.net-web-api asp.net-web-api2

在ASP.NET WebApi 2中,以下内容之间有什么区别:

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);
}
Run Code Online (Sandbox Code Playgroud)

Ant*_*Chu 25

此代码返回result将无法编译,因为result没有实现IHttpActionResult...

public <IHttpActionResult> GetItem(Guid id)
{
    // ... code ..., Item result = ....
    return result;
}
Run Code Online (Sandbox Code Playgroud)

Json()无论传入请求的Accept标头中的格式是什么,返回始终返回HTTP 200并以JSON格式返回结果.

public <IHttpActionResult> GetItem(Guid id)
{
    // ... code ..., Item result = ....
    return Json(result);
}
Run Code Online (Sandbox Code Playgroud)

返回Ok()返回HTTP 200,但结果将根据Accept请求标头中指定的内容进行格式化.

public <IHttpActionResult> GetItem(Guid id)
{
    // ... code ..., Item result = ....
    return Ok(result);
}
Run Code Online (Sandbox Code Playgroud)