无法在asp.net core 2.1的中间件中写入HttpContext的响应主体

问题描述 投票:3回答:4

这是我们中间件的代码片段

public Task InvokeAsync(HttpContext context)
{
    if(!found)
    {
        context.Response.StatusCode = StatusCodes.Status401Unauthorized;
        return context.Response.WriteAsync("Something wrong");
    }
    return _next(context);
}

问题是,虽然客户端应用接收到错误代码401,这很好,但是在响应的正文中找不到“出现错误”字符串。我们在这里缺少什么?

c# middleware asp.net-core-2.1
4个回答
3
投票
以下语句:return context.Response.WriteAsync("Something wrong");

已被替换为:

return context.Response.Body.WriteAsync("Something wrong").AsTask();

此更改使响应可以正确填充。虽然,我还不确定为什么这种响应方式可以有效地解决问题,但最初的方法却行不通。


0
投票
HttpContext.Response.WriteAsync("Something wrong").Wait();

参考:What's the difference between Task.Start/Wait and Async/Await?


0
投票
当前,您可以在装配体装配体HttpResponseWritingExtensions.WriteAsync中找到它。

Microsoft.AspNetCore.Http.Abstractions


0
投票
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); }
© www.soinside.com 2019 - 2024. All rights reserved.