-1

由于某种原因 foo 总是返回一个空的主体:

internal static async Task<string> Foo(HttpContext context)
{
    var response = await Task.Run(() => { return "response"; });
    return response;
}

internal static async Task<string> Bar(HttpContext context, string someParam)
{
    var response = await Task.Run(() => { return "response"; });
    return response;
}
4

2 回答 2

1

我能够重现该行为 -HttpContext在单独的方法中使用单个参数移动处理程序会导致空响应:

WebApplicationBuilder builder = WebApplication.CreateBuilder();
WebApplication app = builder.Build();
app.Map("/Fails", Fails);
app.Map("/Fails1", Fails1);
app.Map("/Works", async (HttpContext c) =>
{
    var response = await Task.Run(() => { return "response"; });
    return response;
});
app.Map("/WorksToo", Works);
app.Map("/WorksToo1", Works1);
app.Map("/WorksToo2", Works2);
app.Run();
static async Task<string> Fails1(HttpContext context)
{
    var response = await Task.FromResult("response");
    return response;
}
public partial class Program
{
    internal static async Task<string> Fails(HttpContext context) => await Task.FromResult("response");

    internal static async Task<string> Works(HttpContext context, string someParam) => await Task.FromResult("response");

    internal static async Task<string> Works1(HttpContext context, ILogger<Program> _) => await Task.FromResult("response");

    internal static async Task<string> Works2(HttpRequest context) => await Task.FromResult("response");
}

在github上发布了新问题。现在,您可以像我一样将虚拟参数添加到处理程序Works1

于 2022-02-03T13:03:51.873 回答
0

也许您必须等待任务完成才能查看返回的Task实例的Result属性中设置的内容。

我在控制台应用程序中编写了几乎相同的代码(没有HttpContext参数),我注意到当您在代码中使用Result属性时,您的Foo()方法返回的结果就在那里。它可能会触发任务等待完成。

链接:https ://www.pluralsight.com/guides/using-task-run-async-await

于 2022-02-02T22:59:55.103 回答