在代码中设置wcf端点头

时间:2010-12-06 12:32:58

标签: wcf header

配置中设置端点标头的代码等效是什么?

<client>
<endpoint address="http://localhost/..." >
<headers>
<something>blah</something>
</headers>
</endpoint>

2 个答案:

答案 0 :(得分:4)

不需要创建新的OperationContextScope并在每次使用客户端时设置标题的替代方法是在创建EndpointAddress时指定标题。

示例(改编自https://stackoverflow.com/a/5340009/35233

var binding = new WSHttpBinding ();
var address = new EndpointAddress (
    new Uri (RemoteAddress),
    new AddressHeader[] {
        AddressHeader.CreateAddressHeader ("APIKey", "", "bda11d91-7ade-4da1-855d-24adfe39d174")
    });

var client = new ExampleClient (binding, address);

答案 1 :(得分:2)

这有效:

var header = MessageHeader.CreateHeader("something", "", "blah");

using (new OperationContextScope(channel))
{
  OperationContext.Current.OutgoingMessageHeaders.Add(header);

  //your normal call here
}