Search code examples
asp.net-core-mvchttp-headers

HTTP Response headers collection cannot be modified in .NET Core web app


I have this controller:

[PushHeaderAttribute]
 public class ClockController : Controller
 {

 }

Where PushHeaderAttribute is defined as follows:

public class PushHeaderAttribute : ResultFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext context)
    {
        context.HttpContext.Response.Headers.Remove("Server");
        context.HttpContext.Response.Headers.Add("content-encoding", System.Text.Encoding.UTF8.WebName);
        context.HttpContext.Response.Headers.Add("connection", "keep-alive ");
        base.OnResultExecuting(context);
    }
}

The attribute is called, but when debugging, the context.HttpContext.Response.Headers list is empty, however, when monitoring the response, all the headers are there.

How can I properly manipulate headers in .NET Core Web App?


Solution

  • The base headers likeServer can't be removed,because it haven't be added in your scenario,it would be added in Kestrel/IIS 's intrenal Pipe

    If you do want to remove "Server" response header,you could configure as below for Kestrel(.Net 6 +):

    builder.WebHost.ConfigureKestrel(op => 
    {
        op.AddServerHeader = false;
    });
    

    For IIS, you could refer this article

    For Connection header ,you could check comment in the source codes of HttpProtocol.cs

    // "This means that an intermediary transforming an HTTP/1.x message to HTTP/2 will need to remove any header fields
            // nominated by the Connection header field, along with the Connection header field itself.
            // Such intermediaries SHOULD also remove other connection-specific header fields, such as Keep-Alive,
            // Proxy-Connection, Transfer-Encoding, and Upgrade, even if they are not nominated by the Connection header field."
            //
            // Http/3 has a similar requirement: https://quicwg.org/base-drafts/draft-ietf-quic-http.html#name-field-formatting-and-compre