在我的WEB API中,所有方法都是异步的.
如果我希望客户端进行内容协商,那么应该是API操作方法的返回类型任务< IActionresult>或任务< SomePOCO>
如果我希望方法总是以JSON格式返回数据,那么应该返回API动作方法的类型?应该是Task< IActionResult>或任务< JsonResult>或任务< SomePOCO>因为我认为所有3个都会工作所以不确定哪一个适合这里?
解决方法
If I want [the] client to do content negotiation then what should be the return type of the API action method?
要进行内容协商,请返回Task< ObjectResult>或任务< MyPoco>.
框架自动将POCO包装在ObjectResult中;因此,两个选项都是等价的,并且都将遵循HTTP Accept标头.您还将通过返回实现ObjectResult的任何结果来获得内容协商,例如OkObjectResult.
If I want [the] method to always return data in JSON format then what should be [the] return type of the API action method?
要始终返回JSON,请返回Task< JsonResult> (或使用[Produces]过滤器).
另见:https://docs.asp.net/en/latest/mvc/models/formatting.html#content-negotiation
[S]o I am assuming then
IActionResult
is only used for MVC controller?
IActionResult是Controller返回的所有结果的合同.如果您的操作的签名具有IActionResult返回类型,那么您的操作的方法体可以返回任何结果类型,因为它们都实现了IActionResult接口.这是继承层次结构.
IActionResult ActionResult ChallengeResult ContentResult EmptyResult FileResult FileContentResult FileStreamResult PhysicalFileResult VirtualFileResult ForbidResult LocalRedirectResult ObjectResult CreatedAtActionResult CreatedAtRouteResult CreatedResult BadRequestObjectResult NotFoundObjectResult OkObjectResult RedirectResult RedirectToActionResult RedirectToRouteResult SignInResult SignOutResult StatusCodeResult NoContentResult NotFoundResult OkResult UnauthorizedResult UnsupportedMediaTypeResult BadRequestResult
另见:https://github.com/aspnet/Mvc/tree/dev/src/Microsoft.AspNetCore.Mvc.Core