Pregunta

I'm on Web API self-host and I need to send to the client a keep-alive: close header for each request (I want a new connection each time). How can I set this global configuration?

¿Fue útil?

Solución

You can use a HttpMessageHandler to global make changes to every request/response. The header you are looking for is the Connection header. This header has been exposed a little differently for some reason. You cannot set the Connection header directly, you need to set the ConnectionClose property to true instead.

Create a class like this:

public class CloseConnectionHandler : DelegatingHandler
    {
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {
            return base.SendAsync(request, cancellationToken).ContinueWith(t =>
                {
                    var response = t.Result;
                    response.Headers.ConnectionClose = true;
                    return response;
                });
        }
    }

and add it to your messagehandler collection,

     config.MessageHandlers.Add(new CloseConnectionHandler());

I am curious as to why you would want to do this. The only reason I can imagine is that you are expecting thousands of concurrent clients who each only make one request within any short period of time. Is that the case? If not, you may be incurring a fairly significant performance hit. The Http.sys stack will automatically close connections after 2 mins of inactivity, so it's not like you are leaking connections.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top