【问题标题】:Using Custom Http Header in WCF在 WCF 中使用自定义 Http 标头
【发布时间】:2013-03-12 14:11:11
【问题描述】:

我尝试使用 SOA 服务。我从 wsdl 生成一个服务引用,然后用我的绑定配置实例化一个客户端对象,它是一个 basicHttpBinding。

然后我实现了一个自定义行为和一个消息检查器,并在那里添加了我的自定义标头属性,如下所示...

    public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel)
    {
        request.Properties.Add("CONTENT-TYPE", "text/xml;charset=UTF-8");
        request.Properties.Add("PropertyOne", "One");
        request.Properties.Add("PropertyTwo", "Two");

        return null;
    }

然后,当我尝试使用该服务时,我总是收到错误消息

(502) 网关错误。

使用提琴手,我查看发送到服务的原始 http 数据,自定义属性不在标头中。

【问题讨论】:

    标签: c# wcf http-headers


    【解决方案1】:

    要将自定义 HTTP 标头添加到消息中,您需要将它们添加到消息属性包的 HttpRequestMessageProperty 实例中:

    public object BeforeSendRequest(ref Message request, IClientChannel channel)
    {
        HttpRequestMessageProperty prop;
        if (request.Properties.ContainsKey(HttpRequestMessageProperty.Name))
        {
            prop = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];
        }
        else
        {
            prop = new HttpRequestMessageProperty();
            request.Properties.Add(HttpRequestMessageProperty.Name, prop);
        }
    
        prop.Headers["Content-Type"] = "text/xml; charset=UTF-8";
        prop.Headers["PropertyOne"] = "One";
        prop.Headers["PropertyTwo"] = "Two";
    
        return null;
    }
    

    【讨论】:

      【解决方案2】:

      我也想做类似的事情,并且幸运地使用了 WeboperationContext

      WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.Accepted; WebOperationContext.Current.OutgoingResponse.Headers.Add("HeaderName", "HeaderValue");

      它就像一个魅力

      【讨论】:

      • 包装代码会受到很多人的青睐。编写代码并按 Ctrl + K 即可。
      猜你喜欢
      • 2011-04-27
      • 2012-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-10
      • 1970-01-01
      • 2012-01-17
      相关资源
      最近更新 更多