Search code examples
c#asp.net-core-webapikeep-alivekestrel-http-serverasp.net-core-6.0

Unable to set response header "Connection" in ASP.NET Core 6


I have an ASP.NET Core 6 Web API and the requirement to set a Connection: Close header in certain situations to put some legacy terminals (client) in a maintenance mode.

I can set the headers in general, but the Connection: Close header gets removed and is not part of the response.

Here is my controller:

[ApiController]
[Route("[controller]")]
public class HeaderTestController : ControllerBase
{
    [HttpGet]
    public IActionResult Get()
    {
        Response.Headers.Add("Foo", "Bar");           // part of the response
        Response.Headers.Add("Connection", "close");  // NOT part of the response

        return NoContent();
    }
}

This is how my Program.cs looks like:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();

var app = builder.Build();

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();

app.Run();

When I invoke the API method, it returns the foo header but omits the Connection header:

enter image description here

Any idea which component is removing the Connection header and how I can bypass it?


Solution

  • Check method CreateResponseHeaders in HttpProtocol.cs. it is removing this header here. and I don't think any ways to bypass it.

    and also this is only removed if client is making http/2 or http/3 request. if your legacy client is still using http/1.1 then it won't be removed.

    Hope this helps.