在WCF中使用自定义Http标头

时间:2013-03-12 14:11:12

标签: c# wcf http-headers

我尝试使用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)Bad Gateway。

使用fiddler我查看发送给服务的原始http数据,自定义属性不在标题中。

2 个答案:

答案 0 :(得分:3)

要向邮件添加自定义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;
}

答案 1 :(得分:0)

I wanted to do something similar too and had luck with WeboperationContext

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

and it worked like a charm