How do I prevent my .NET SOAP client from including “Connection: KeepAlive” in the HTTP headers. (using WSE3.0)

穿精又带淫゛_ 提交于 2019-12-05 05:45:26

One solution is to override the GetWebRequest(Uri uri) method.
The information which lead me to this solution was found on this MSDN Forum Post

Method 1: Modify the Auto Generated file.

Paste this snippet into the Reference.cs file which was automatically generated for you. The downside of this approach is if you ever regenerate the web service client adapters (ie Update Web References) you will have to then modify the file again.

protected override System.Net.WebRequest GetWebRequest(Uri uri)
{
    System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)base.GetWebRequest(uri);
    webRequest.KeepAlive = false;
    return webRequest;
}

Method 2: Create a partial class

Create a file and paste the following code into it. Modify the namespace and class name so they match your webservice.

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;
        }
    }
}

Notes

This approach may work if you do not use WSE. I was able to paste the method above under the non WSE webservice class... which extends System.Web.Services.Protocols.SoapHttpClientProtocol. From my testing it appeared that this made it not include any Http Connection line at all where as when I did it inside a WSE class (which are derived from Microsoft.Web.Services3.WebServicesClientProtocol) it then included a "Connection: Close" line. According to 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

So, while it may not include KeepAlive in the header anymore... I think in HTTP1.1 it's assumed to be the default.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!