简体   繁体   中英

how to modify http header of request; web reference in C#

I'm creating a .NET application that uses a web service. I need set the connection http header to "closed" in the request to that web service. I've been Googling this for a day but have not been able to get anything to work.

My best effort is the code below, which attempts to override the GetWebRequest method to add the header. This appears to fail - I place a breakpoint in it, and when I run my application, the breakpoint is never hit and the connection header does not appear to be set (I'm evaluating this not by viewing the http header but by the behavior of the system handling the web request).

Some information: when I added the web reference, using Visual Studio, I right-clicked on the project in the solution explorer, chose "Add Service Reference", "Advanced", then "Add Web Reference".

namespace System.Net
{
    public class MyHttpProtocol : SoapHttpClientProtocol
    {
        protected override WebRequest GetWebRequest(Uri uri)
        {
            HttpWebRequest webRequest = (HttpWebRequest)base.GetWebRequest(uri);
            webRequest.Headers.Add("connection", "closed");
            return webRequest;
        }
    }
}

You need to use an IClientMessageInspector to alter the request as it's being constructed. This question is very similar and should give you the answer.

Many things in WCF involve creating behaviours and specifying them in the web config to override certain aspects of the process, which can be a bit fiddly but is very powerful. You can add your request in there.

Edit to address your comment, does your code look like this?

public object BeforeSendRequest(
    ref System.ServiceModel.Channels.Message request,
    System.ServiceModel.IClientChannel channel)
{
    var httpRequestMessage = new HttpRequestMessageProperty();
    httpRequestMessage.Headers.Add("connection", "closed");
    request.Properties.Add(
        HttpRequestMessageProperty.Name, httpRequestMessage);
    return null;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM