遗憾的是,没有设法找到任何涉及这方面的帖子。
我创建了一个WebAPI应用程序(ASP.NET Core 2.1)并使用NSwag,我用它来自动生成typescript服务代理。
我见过代码示例,其中JsonResult
和ActionResult
由控制器操作返回。
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);
}
}
参考Controller action return types in ASP.NET Core Web API
ActionResult<T>
typeASP.NET Core 2.1为Web API控制器操作引入了
ActionResult<T>
返回类型。它使您能够返回从ActionResult
派生的类型或返回特定类型。 ActionResult比IActionResult类型提供以下好处:
- 可以排除
[ProducesResponseType]
属性的Type属性。例如,[ProducesResponseType(200, Type = typeof(Product))]
被简化为[ProducesResponseType(200)]
。该行动的预期收益类型是从T
的ActionResult<T>
推断出来的。- 隐式强制转换运算符支持
T
和ActionResult
转换为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;
}