在 HTTP 连接 header 中,我的 Web 服务客户端包括:
连接:保持事件
我想禁用此功能。 经过一些研究,似乎实现此目的的方法是将 SoapHttpChannelOptions
类的 KeepAlive 成员设置为 false。但是,我没有看到在使用 WSE3.0(Web 服务增强)在 Visual Studio 中为我生成的 Web 服务客户端类 中访问/修改 SoapHttpChannelOptions
的方法。
在我的例子中,生成的 stub 类扩展了Microsoft.Web.Services3.WebServicesClientProtocol
我在谷歌上找不到任何示例,SoapHttpChannelOptions 类的大多数成员都继承到 WebServicesClientProtocol 类中...
SoapHttpChannelOptions Reference
WebServicesClientProtocol Reference
注意:我并没有尝试修改网络服务器。我正在尝试修改 Web 服务客户端。
最佳答案
一种解决方案是重写 GetWebRequest(Uri uri)
方法。
引导我找到这个解决方案的信息是在这个MSDN Forum Post上找到的。
方法一:修改自动生成的文件。
将此代码段粘贴到自动为您生成的 Reference.cs 文件中。这种方法的缺点是,如果您重新生成 Web 服务客户端适配器(即更新 Web 引用),则必须再次修改该文件。
protected override System.Net.WebRequest GetWebRequest(Uri uri)
{
System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)base.GetWebRequest(uri);
webRequest.KeepAlive = false;
return webRequest;
}
方法2:创建分部类
创建一个文件并将以下代码粘贴到其中。修改命名空间和类名称,使其与您的 Web 服务匹配。
namespace YourNamespace
{
using System.Diagnostics;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Xml.Serialization;
/// <summary>
/// This partial class makes it so all requests specify
/// "Connection: Close" instead of "Connection: KeepAlive" in the HTTP headers.
/// </summary>
public partial class YourServiceNameWse : Microsoft.Web.Services3.WebServicesClientProtocol
{
protected override System.Net.WebRequest GetWebRequest(Uri uri)
{
System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)base.GetWebRequest(uri);
webRequest.KeepAlive = false;
return webRequest;
}
}
}
注释
如果您不使用 WSE,此方法可能有效。我能够将上面的方法粘贴到非 WSE Webservice 类下...它扩展了 System.Web.Services.Protocols.SoapHttpClientProtocol。从我的测试来看,这使得它根本不包含任何 Http Connection 行,就像我在 WSE 类(派生自 Microsoft.Web.Services3.WebServicesClientProtocol
)中执行此操作时,它然后包含“连接:关闭”行。根据this site on HTTP KeepAlive :
Under HTTP 1.1, the official keepalive method is different. All connections are kept alive, unless stated otherwise with the following header: Connection: close
所以,虽然它可能不再在 header 中包含 KeepAlive...我认为在 HTTP1.1 中它被假定为默认值。
关于.net - 如何防止 .NET SOAP 客户端在 HTTP header 中包含 "Connection: KeepAlive"。 (使用WSE3.0),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1527407/