Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IHttpActionResult difference between returning item, Json(item) and Ok(item)

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);
}
like image 925
Adam Szabo Avatar asked Apr 20 '14 22:04

Adam Szabo


1 Answers

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);
}
like image 54
Anthony Chu Avatar answered Oct 19 '22 18:10

Anthony Chu