返回ActionResult而不拆包任务

时间:2019-06-15 17:18:59

标签: c# asp.net-core .net-core

我经常遇到这种情况,我需要返回服务,然后再将ActionResult从控制器中退回。

public Task<ActionResult<Foo>> Action(int id)
{
    // Task<Foo> cannot be casted to Task<ActionResult<Foo>>
    return _fooService.Details(id); 
}

服务返回的任务不能隐式转换为ActionResult<Foo>,因此我最终在控制器中解压缩了任务。像这样

public async Task<ActionResult<Foo>> Action(int id)
{
    return await _fooService.Details(id);
    // Both work
    return BadRequest();
}

如果我不将其包装在ActionResult中,则可以通过任务,但不能返回其他类型的IActionResults

public Task<Foo> Action(int id)
{
    return _fooService.Details(id); // <--- pass-through Task

    return BadRequest() // <-- But, I can't do this
}

我的问题是,有没有办法设置从Task<T>ActionResult<T>的转换,而又不通过隐式运算符使动作异步?

1 个答案:

答案 0 :(得分:3)

您忘记在 Task 之前提及 async

Public Sub NCRDtFltr()
If IsNull(Me.Combo58.Value) And Me.Option54 = True Then
    Filter = "([Date] Between #" & Format([TxtDtStrt], "yyyy\/mm\/dd") & "# And #" & Format([TxtDtEnd], "yyyy\/mm\/dd") & "#) And ([NCR Clsd?]=False)"
End If
If IsNull(Me.Combo58.Value) And Me.Option56 = True Then
    Filter = "([Date] Between #" & Format([TxtDtStrt], "yyyy\/mm\/dd") & "# And #" & Format([TxtDtEnd], "yyyy\/mm\/dd") & "#) And ([NCR Clsd?]=True)"
End If
If IsNull(Me.Combo58.Value) And Me.Option54 = False And Me.Option56 = False Then
    Filter = "[Date] Between #" & Format([TxtDtStrt], "yyyy\/mm\/dd") & "# And #" & Format([TxtDtEnd], "yyyy\/mm\/dd") & "#"
End If

If Not IsNull(Me.Combo58.Value) And Me.Option54 = True Then
    Filter = "([Date] Between #" & Format([TxtDtStrt], "yyyy\/mm\/dd") & "# And #" & Format([TxtDtEnd], "yyyy\/mm\/dd") & "#) And ([OpDescription]=" & ([Combo58]) & ")And ([NCR Clsd?]=False)"
End If
If Not IsNull(Me.Combo58.Value) And Me.Option56 = True Then
    Filter = "([Date] Between #" & Format([TxtDtStrt], "yyyy\/mm\/dd") & "# And #" & Format([TxtDtEnd], "yyyy\/mm\/dd") & "#) And ([OpDescription]=" & ([Combo58]) & ")And ([NCR Clsd?]=True)"
    End If
If Not IsNull(Me.Combo58.Value) And Me.Option54 = False And Me.Option56 = False Then
    Filter = "([Date] Between #" & Format([TxtDtStrt], "yyyy\/mm\/dd") & "# And #" & Format([TxtDtEnd], "yyyy\/mm\/dd") & "#) And ([OpDescription]=" & ([Combo58]) & ")"
End If
End Sub