从WebAPI控制器返回DTO

时间:2018-09-08 13:56:32

标签: c# asp.net asp.net-web-api asp.net-core asp.net-core-webapi

不幸的是,我们未能找到涉及此方面的任何帖子。

我创建了一个WebAPI应用程序(ASP.NET Core 2.1),并利用了NSwag来自动生成打字稿服务代理。

我看过一些代码示例,其中控制器动作返回了JsonResultActionResult

DTO通常属于服务层,所以我想知道是否可以将它们用作控制器操作输出。

我想知道从控制器操作返回DTO是否正确。

控制器

[Route("api/[controller]/[action]")]
[Authorize]
public class EntryController : ControllerBase
{
    private readonly IEntryService _entryService;

    public EntryController(
        IEntryService entryService
        )
    {
        _entryService = entryService;
    }

    public async Task<List<EntryDto>> GetMany(long id)
    {
        var result = await _entryService.GetMany(id);
        return result;
    }
}

服务

public class EntryService : BaseService, IEntryService
{
    private readonly IEntryHighPerformanceService _entryHighPerformanceService;

    public EntryService(
        AppDbContext context,
        IEntryHighPerformanceService entryHighPerformanceService,
        SessionProvider sessionProvider
        ) : base(
              context,
              sessionProvider
              )
    {
        _entryHighPerformanceService = entryHighPerformanceService;
    }

    public async Task<List<EntryDto>> GetMany(long id)
    {
        var dtos = _entryHighPerformanceService.GetByVocabularyId(id);
        return await Task.FromResult(dtos);
    }
}

1 个答案:

答案 0 :(得分:1)

引用Controller action return types in ASP.NET Core Web API

  

ActionResult<T>类型

     

ASP.NET Core 2.1为Web API控制器操作引入了ActionResult<T>返回类型。它   使您能够返回源自ActionResult的类型或返回   具体类型。与   IActionResult类型:

     
      
  • [ProducesResponseType]属性的Type属性可以是   排除在外。例如,[ProducesResponseType(200, Type = typeof(Product))]简化为[ProducesResponseType(200)]。的   相反,操作的预期返回类型是从T   ActionResult<T>
  •   
  • 隐式强制转换运算符支持转换   TActionResultActionResult<T>中的一个。 T转换为   ObjectResult,这意味着return new ObjectResult(T);是   简化为return T;
  •   

以您的控制器为例

[HttpGet]
public async Task<ActionResult<List<EntryDto>>> GetMany(long id) {
    //lets say we wanted to validate id
    if(id < 1) {
        return BadRequest("id must be greater than zero (0)");
    }

    var result = await _entryService.GetMany(id);
    if(result == null || result.Count == 0) {
        return NotFound(); // returns proper response code instead of null
    }
    return result;
}