简体   繁体   English

如何修改请求的http头; C#中的Web参考

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

I'm creating a .NET application that uses a web service. 我正在创建一个使用Web服务的.NET应用程序。 I need set the connection http header to "closed" in the request to that web service. 我需要在对该Web服务的请求中将连接http标头设置为“已关闭”。 I've been Googling this for a day but have not been able to get anything to work. 我已经在Google上搜索了整整一天,但没有任何东西可以工作。

My best effort is the code below, which attempts to override the GetWebRequest method to add the header. 我最大的努力是下面的代码,该代码尝试覆盖GetWebRequest方法以添加标头。 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). 这似乎失败-我在其中放置一个断点,并且在运行应用程序时,断点从未被击中,并且似乎未设置连接头(我不是通过查看http头而是通过行为来进行评估)处理Web请求的系统)。

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". 一些信息:使用Visual Studio添加Web参考时,我在解决方案资源管理器中的项目上单击鼠标右键,依次选择“添加服务参考”,“高级”,“添加Web参考”。

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. 您需要使用IClientMessageInspector更改正在构造的请求。 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. WCF中的许多事情都涉及创建行为并在Web配置中指定行为以覆盖过程的某些方面,这可能有点儿怪异,但功能非常强大。 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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