IActionResult vs ObjectResult vs JsonResult in ASP.NET Core API

14,027

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

Share:
14,027
Sam
Author by

Sam

Updated on July 28, 2022

Comments

  • Sam
    Sam almost 2 years

    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();
    }