从 WebAPI 控制器返回 DTO

不幸的是,还没有找到任何涉及这方面的帖子。


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


我看过控制器操作返回JsonResult& 的代码示例ActionResult。


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


我想知道从控制器操作返回 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);

    }

}


一只萌萌小番薯
浏览 333回答 1
1回答

千万里不及你

参考ASP.NET Core Web API 中的控制器操作返回类型ActionResult<T>&nbsp;类型ASP.NET Core 2.1 引入了ActionResult<T>Web API 控制器操作的返回类型。它使您能够返回派生自ActionResult或返回特定类型的类型。与 IActionResult 类型相比,ActionResult 具有以下优点:该[ProducesResponseType]属性的类型属性可以被排除。例如,[ProducesResponseType(200, Type = typeof(Product))]简化为[ProducesResponseType(200)]。操作的预期返回类型是从Tin&nbsp;推断出来的ActionResult<T>。隐式转换运营商支持的转换T和ActionResult到ActionResult<T>。T转换为&nbsp;ObjectResult,这意味着return new ObjectResult(T);简化为return T;。以你的控制器为例[HttpGet]public async Task<ActionResult<List<EntryDto>>> GetMany(long id) {&nbsp; &nbsp; //lets say we wanted to validate id&nbsp; &nbsp; if(id < 1) {&nbsp; &nbsp; &nbsp; &nbsp; return BadRequest("id must be greater than zero (0)");&nbsp; &nbsp; }&nbsp; &nbsp; var result = await _entryService.GetMany(id);&nbsp; &nbsp; if(result == null || result.Count == 0) {&nbsp; &nbsp; &nbsp; &nbsp; return NotFound(); // returns proper response code instead of null&nbsp; &nbsp; }&nbsp; &nbsp; return result;}
打开App,查看更多内容
随时随地看视频慕课网APP