这是我们中间件的代码片段
public Task InvokeAsync(HttpContext context)
{
if(!found)
{
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
return context.Response.WriteAsync("Something wrong");
}
return _next(context);
}
问题是,虽然客户端应用接收到错误代码401,这很好,但是在响应的正文中找不到“出现错误”字符串。我们在这里缺少什么?
return context.Response.WriteAsync("Something wrong");
已被替换为:
return context.Response.Body.WriteAsync("Something wrong").AsTask();
此更改使响应可以正确填充。虽然,我还不确定为什么这种响应方式可以有效地解决问题,但最初的方法却行不通。
HttpContext.Response.WriteAsync("Something wrong").Wait();
参考:What's the difference between Task.Start/Wait and Async/Await?
HttpResponseWritingExtensions.WriteAsync
中找到它。Microsoft.AspNetCore.Http.Abstractions
using Microsoft.AspNetCore.Http;
public Task InvokeAsync(HttpContext context)
{
if (found == false)
{
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
await HttpResponseWritingExtensions.WriteAsync(context.Response, "Something wrong");
}
return _next(context);
}