Search code examples
c#asp.net-corehttp-headerskeep-aliveasp.net-core-webapi

How to make keep-alive header response?


I try to make simple Web API application with GET and POST.When I response to a GET request:

 {
    "status": "OK",
    "headers":
    {
        "Date": "Fri, 18 Aug 2017 16:50:38 GMT",
        "Transfer-Encoding": "chunked",
        "Connection": "close",
        "Content-Type": "application/json; charset=utf-8",
        "Server": "Kestrel"
    },
    "body": "....",
    "code": 200,
    "protocol": "HTTP/1.1"
}

But I want to make "Connection": "keep-alive", not "Connection": "close" so I changed my config.

Startup.cs:

 public void Configure(IApplicationBuilder app,
                       IHostingEnvironment env,
                       ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();
    app.UseMvc();
    app.UseSession();
    app.Run(async (context) =>
    {
        context.Response.Headers[HeaderNames.Connection] = "Keep-Alive";
    });                    
}

But, I get a "Connection": "close" response.

Any idea how to change to the "keep-alive" setting?


Solution

  • HTTP/1.1 defines the "close" connection option for the sender to signal that the connection will be closed after completion of the response. For example, Connection: close in either the request or the response header fields indicates that the connection SHOULD NOT be considered `persistent' after the current request/response is complete.

    If you are trying to achieve a persistent connection, you may want to look into websockets.