Reputation: 923
Did I get it right?
I'm writing a Web API in .Net Core.
StatusCodeResult: use it, if you want just to return a status code without any content/data.
ObjectResult: if I want to return a status code and some data.
For example: a client makes a request: get person with id=1. In this case I would use OkObjectResult. If the id is not available I could return NotFoundResult (or NotFoundObjectResult if I would like to return some data like an error message).
Upvotes: 1
Views: 1236
Reputation: 9993
Yes, You are right. From the Microsoft Document:
StatusCodeResult:
Represents an ActionResult that when executed will produce an HTTP response with the given response status code.
ObjectResult:
An ActionResult that on execution will write an object to the response using mechanisms provided by the host.
From your example, You can just return NotFound()
.
Let's check the constructor method of NotFound()
:
When you don't pass any parameter, The return type is NotFoundResult
, It will just show an empty 404 response. But when you pass a parameter into 'NotFound(xx)', The return type is NotFoundObjectResult
, It will show the 404 responses with the passed object.
Refer to this simple demo:
[HttpPost]
public IActionResult Get(int id)
{
if (id == 3)
{
//only return 200 state code
return Ok();
}
else
{
//return 404 state code with error message.
return NotFound("Id is not correct");
}
Upvotes: 1