retif
retif

Reputation: 1652

UseExceptionHandler() middleware in .NET Core MVC prevents response headers setting

Startup.cs:

// ...
app.Use(async (context, next) =>
{
    context.Response.Headers.Add("X-Frame-Options", "DENY");
    context.Response.Headers.Add("X-Content-Type-Options", "nosniff");
    context.Response.Headers.Add("Server", "ololo");

    await next();
});

if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); }
else { app.UseExceptionHandler("/Home/Error"); }

app.UseStaticFiles();
app.UseAuthentication();
// ...

When everything is fine, I get the following headers, as expected:

HTTP/1.1 200 OK
Connection: close
Date: Mon, 30 Jul 2018 18:39:33 GMT
Content-Type: text/html; charset=utf-8
Server: ololo
Transfer-Encoding: chunked
X-Frame-Options: DENY
X-Content-Type-Options: nosniff

So Server, X-Frame-Options and X-Content-Type-Options headers are overridden.

But if I have an unhandled exception in my code, then I get these headers:

HTTP/1.1 500 Internal Server Error
Connection: close
Date: Mon, 30 Jul 2018 18:35:49 GMT
Content-Type: text/html; charset=utf-8
Server: Kestrel
Cache-Control: no-cache
Pragma: no-cache
Transfer-Encoding: chunked
Expires: -1

So headers are not overridden.

Why is that? Is it by design? Does Exceptions middleware work differently so it doesn't go through the whole pipeline?

dotnet --info
.NET Command Line Tools (2.1.4)

Product Information:
 Version:            2.1.4
 Commit SHA-1 hash:  5e8add2190

Microsoft .NET Core Shared Framework Host

  Version  : 2.0.5
  Build    : 17373eb129b3b05aa18ece963f8795d65ef8ea54

Upvotes: 3

Views: 1101

Answers (1)

Tseng
Tseng

Reputation: 64288

A more reliable way to set the headers in any case would be to use the OnStarting callback. See docs.

Adds a delegate to be invoked just before response headers will be sent to the client.

public async Task Invoke(HttpContext context)
{
    context.Response.OnStarting(() =>
    {
        context.Response.Headers.Add("X-Frame-Options", "DENY");
        context.Response.Headers.Add("X-Content-Type-Options", "nosniff");
        context.Response.Headers.Add("Server", "ololo");

        return Task.CompletedTask;
    });

    await _next(context);
}

OnStarting will be invoked, just before the response headers are written to the wire. This allows you to set the headers after the exception middleware did handle it

Upvotes: 6

Related Questions