简体   繁体   English

在WCF中使用自定义Http标头

[英]Using Custom Http Header in WCF

i try to consume a SOA Service. 我尝试使用SOA服务。 I generate a Service Reference from the wsdl and then I instantiate a client object with my binding configuration, it is a basicHttpBinding. 我从wsdl生成一个服务引用,然后用我的绑定配置实例化一个客户端对象,它是一个basicHttpBinding。

Then i implement a custom behavior and a message inspector and there I add my custom header properties like shown below... 然后我实现了自定义行为和消息检查器,在那里我添加了我的自定义标题属性,如下所示...

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

Then, when I try to consume the service, I get always the Error message 然后,当我尝试使用该服务时,我总是得到错误消息

(502) Bad Gateway. (502错误的网关。

With fiddler I look at the raw http data send to the service, the custom properties aren't in the header. 使用fiddler我查看发送到服务的原始http数据,自定义属性不在标题中。

To add a custom HTTP header to a message, you need to add them to the HttpRequestMessageProperty instance of the message property bag: 要向邮件添加自定义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;
}

I wanted to do something similar too and had luck with WeboperationContext 我也想做类似的事情并且幸运地使用了WeboperationContext

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

and it worked like a charm 它就像一个魅力

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

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