Reputation: 30334
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();
}
Upvotes: 9
Views: 19367
Reputation: 247451
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
Upvotes: 24