Reputation: 923
(a)
var person = repository.GetPerson(id)
return person;
(b)
var person = repository.GetPerson(id)
return Ok(person);
According to the developer tools the result is the same and the status code is always 200. Is there a difference? If there is no difference, should I use the Ok() method or OkResult anyway?
Upvotes: 2
Views: 2274
Reputation: 6531
Another difference is caused by the two implicit conversions on ActionResult<T>
.
One is from the regular ActionResult
. Ok("string)
is an ActionResult
(more specifically an OkObjectResult
). So a method that returns ActionResult<User>
will allow return Ok("string")
.
The second implicit conversion is from T
. So return new User()
will also be implicitly converted to ActionResult<User>
.
This means that, while Ok(object)
is very useful and arguably more explicit, the compiler is more likely to surface a type error if you avoid using Ok()
and stick to returning the actual object.
Upvotes: 4
Reputation: 21729
Assuming both are examples are code inside an endpoint for an HTTP GET call, they are effectively the same.
There might be a slight difference in implementation, but the net result will be the same: the payloads in either case are identical (e.g. JSON or some other representation), and the status code will be identical, 200
.
It's a good practice to be explicit though, and use return Ok(person)
because this is both succinct and reveals the intent more obviously than return person
. You could also do return new OkObjectResult(person)
, which is intention revealing but not succinct. (ref: OkObjectResult).
Finally, OkResult should only be used when you don't want to return a payload. This is equivalent to return Ok()
.
Upvotes: 5