从Web API控制器返回DTO

问题描述 投票:1回答:1

遗憾的是,没有设法找到任何涉及这方面的帖子。

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

我见过代码示例,其中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);
    }
}
c# asp.net asp.net-web-api asp.net-core asp.net-core-webapi
1个回答
1
投票

参考Controller action return types in ASP.NET Core Web API

ActionResult<T> type

ASP.NET Core 2.1为Web API控制器操作引入了ActionResult<T>返回类型。它使您能够返回从ActionResult派生的类型或返回特定类型。 ActionResult比IActionResult类型提供以下好处:

  • 可以排除[ProducesResponseType]属性的Type属性。例如,[ProducesResponseType(200, Type = typeof(Product))]被简化为[ProducesResponseType(200)]。该行动的预期收益类型是从TActionResult<T>推断出来的。
  • 隐式强制转换运算符支持TActionResult转换为ActionResult<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;
}
© www.soinside.com 2019 - 2024. All rights reserved.