Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IActionResult vs ObjectResult vs JsonResult in ASP.NET Core API

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();
}
like image 975
Sam Avatar asked Oct 19 '17 14:10

Sam


People also ask

What is difference between ActionResult and IActionResult?

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.

What is ObjectResult?

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.

What are the return types in net core Web API?

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.

Which is the IActionResult that has content negotiation built in asp net core Web API?

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.


1 Answers

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

like image 168
Nkosi Avatar answered Sep 22 '22 04:09

Nkosi