Jerald Baker
Jerald Baker

Reputation: 1369

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

I have this setup :

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

I need to set the response body in Middleware2 and add some headers in Middleware1.

If I do a httpContext.Response.WriteAsync(..) in Middleware2, then I can't set the headers in Middleware1 as it results in an exception that says

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

How to achieve this?

*other than wrapping the httpContext with a custom field to hold the output temporarily and then writeAsync() on original responseStream in the outermost middleware.

Upvotes: 0

Views: 663

Answers (1)

abdusco
abdusco

Reputation: 11101

You can use HttpContext.Response.OnStarting to modify response headers right before they're sent.

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
}

Upvotes: 1

Related Questions