What's the best option to use in a Web API that will return both HTTP status codes
and JSON
results?
I've always used IActionResult
but it was always a Web App with a Web API. This time it's only Web API.
I have the following simple method that's giving me an error that reads:
Cannot implicitly convert type Microsoft.AspNetCore.Mvc.OkObjectResult to System.Threading.Tasks.Task Microsoft.AspNetCore.Mvc.IActionResult
[HttpGet]
public Task<IActionResult> Get()
{
return Ok();
}
The IActionResult return type is appropriate when multiple ActionResult return types are possible in an action. The ActionResult types represent various HTTP status codes. Any non-abstract class deriving from ActionResult qualifies as a valid return type.
ObjectResult is an IActionResult that has content negotiation built in. Inside its ExecuteResultAsync , responsible for writing to the response stream, the framework will walk through the available formatters and select a relevant one.
Note that there are two possible return types in this action. If the employee with the specified id is not found, it returns a 404 Not Found response. On the other hand, once it finds the employee with the specified id, it returns a 200 Ok status code with the employee object.
NET core web APIs, content negotiation works with ObjectResult return type. ObjectResult is derived from ActionResult. So if the API action returns IActionResult, . NET Core automatically wraps the object using ObjectResult concrete implementation and thus content negotiation support is added for those actions.
Return the object that best suits the needs of the request. As for the action's method definition, define it with IActionResult
to allow the flexibility of using an abstraction as apposed to tightly coupled concretions.
[HttpGet]
public IActionResult Get() {
return Ok();
}
The above action would return 200 OK response when called.
[HttpGet]
public IActionResult Get() {
var model = SomeMethod();
return Ok(model);
}
The above would return 200 OK response with content. The difference being that it allows content negotiation because it was not specifically restricted to JSON.
[HttpGet]
public IActionResult Get() {
var model = SomeMethod();
return Json(model);
}
The above will only return Json content type.
A very good article to read on the subject
Asp.Net Core Action Results Explained
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With