IActionResult vs ObjectResult vs JsonResult in ASP.NET Core API

两盒软妹~` 提交于 2021-01-18 04:10:48

问题


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

回答1:


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



来源:https://stackoverflow.com/questions/46832422/iactionresult-vs-objectresult-vs-jsonresult-in-asp-net-core-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!