我有一个这个签名的controller方法,它工作得很好,但我需要做一些请求验证,并相应地返回401、400等代码,这是它不支持的。
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
来使用,而不需要返回任何其他的可能性。
这个应该可以
public ActionResult<IAsyncEnumerable<MyDto>> Get()
{
if(IsRequestInvalid())
{
// now can do.
return Unauthorized();
}
return new ActionResult<IAsyncEnumerable<MyDto>>(DoSomeProcessing());
IAsyncEnumerable<MyDto> DoSomeProcessing()
{
IAsyncEnumerable<MyDto> retrievedDtos = _someService.GetAllDtosAsync(_userId);
await foreach(var currentDto in retrievedDtos)
{
//work with currentDto here
yield return currentDto;
}
}
}
如果在退货前没有处理物品更好。
public ActionResult<IAsyncEnumerable<MyDto>> Get()
{
if(IsRequestInvalid())
{
// now can do
return Unauthorized();
}
return new ActionResult<IAsyncEnumerable<MyDto>>(_someService.GetAllDtosAsync(_userId));
}