Web API保持活动标头 [英] Web API keep-alive header

查看:153
本文介绍了Web API保持活动标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Web API自主机上,我需要向客户端发送每个请求的keep-alive:close标头(我希望每次都有一个新的连接)。如何设置此全局配置?

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?

推荐答案

您可以使用HttpMessageHandler对每个请求/响应进行全局更改。您要查找的标头是连接标头。出于某种原因,此标题的显示略有不同。您不能直接设置连接标头,需要将 ConnectionClose 属性设置为 true 而不是。

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.

创建一个这样的类:

public class CloseConnectionHeader : 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;
                });
        }
    }

并将其添加到您的messagehandler集合中,

and add it to your messagehandler collection,

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

我很好奇你为什么要这样做。我能想象的唯一原因是你期待成千上万的并发客户,每个客户只能在短时间内提出一个请求。是这样的吗?如果没有,您可能会受到相当大的性能影响。 Http.sys堆栈将在2分钟不活动后自动关闭连接,因此它不像是在泄漏连接。

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.

这篇关于Web API保持活动标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆