asp.net-core – 什么应该是WEB API Action Method的返回类型?

我正在使用.NET Core开发ASP.NET Web API.此Web API将主要由UI应用程序访问(UI将使用ASP.NET Core MVC开发),但在将来API也可以由其他应用程序访问.

在我的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

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....