如果内部中间件已写入 body,如何更改中间件中的 headers?

How to alter headers in middleware if inner middleware has written to body?

我有这个设置:

--> MiddleWare1 ---> Middleware2 ---> x,y,z-- > WebMVC

我需要在 Middleware2 中设置响应 body 并在 Middleware1 中添加一些 headers。

如果我在 Middleware2 中执行 httpContext.Response.WriteAsync(..),那么我无法在 Middleware1 中设置 headers,因为它会导致异常

"The response headers cannot be modified because the response has already started."

如何实现?

*除了用自定义字段包装 httpContext 以临时保存输出,然后在最外层中间件中的原始 responseStream 上 writeAsync()。

您可以使用 HttpContext.Response.OnStarting 在发送之前修改响应 headers。

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // other middleware
    app.Use(async (context, next) =>
    {
        context.Response.OnStarting(async () =>
        {
            context.Response.Headers.Add("Custom-Header", "1");
        });
        await next();
    });
    // other middleware
    app.Use((context, next) =>
    {
        return context.Response.WriteAsync("something");
    });
    // other middleware
}