5

我有这个签名的控制器方法:

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为在没有返回其他任何东西的可能性/灵活性的情况下使用。

4

1 回答 1

-1

这应该工作

    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));
    }
于 2020-05-29T08:35:59.637 回答