我有这个签名的控制器方法:
public async IAsyncEnumerable<MyDto> Get()
它工作正常,但我需要做一些请求验证并相应地返回 401、400 和其他代码,它不支持。或者,以下签名无法编译:
public async Task<ActionResult<IAsyncEnumerable<MyDto>>> Get()
错误:
无法将类型“Microsoft.AspNetCore.Mvc.UnauthorizedResult”隐式转换为“MyApi.Responses.MyDto”
完整的方法:
public async IAsyncEnumerable<MyDto> Get()
{
if (IsRequestInvalid())
{
// Can't do the following. Does not compile.
yield return Unauthorized();
}
var retrievedDtos = _someService.GetAllDtosAsync(_userId);
await foreach (var currentDto in retrievedDtos)
{
yield return currentDto;
}
}
有任何想法吗?似乎无法相信微软已经设计IAsyncEnumerable
为在没有返回其他任何东西的可能性/灵活性的情况下使用。