以可靠会话方式程序化地向终结点添加自定义WCF标头

4
我正在构建一个WCF路由器,我的客户端使用可靠会话。在这种情况下,当客户端打开通道时,将发送一条消息(建立可靠会话?)。其内容如下:
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing">
  <s:Header>
    <a:Action s:mustUnderstand="1">http://docs.oasis-open.org/ws-rx/wsrm/200702/CreateSequence</a:Action>
    <a:MessageID>urn:uuid:1758f794-c5d3-4573-b252-7a07344cc257</a:MessageID>
    <a:To s:mustUnderstand="1">http://localhost:8010/RouterService</a:To>
  </s:Header>
  <s:Body>
    <CreateSequence xmlns="http://docs.oasis-open.org/ws-rx/wsrm/200702">
      <AcksTo>
        <a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>
      </AcksTo>
      <Offer>
        <Identifier>urn:uuid:64a12658-71d9-4967-88ec-9bb0610f7ecb</Identifier>
        <Endpoint>
          <a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>
        </Endpoint>
        <IncompleteSequenceBehavior>DiscardFollowingFirstGap</IncompleteSequenceBehavior>
      </Offer>
    </CreateSequence>
  </s:Body>
</s:Envelope>

这里的问题在于头部没有包含任何信息,我无法使用它来查找将消息路由到哪个服务。在Busatmante的路由器示例代码中,她通过向终端添加一个标题来解决这个问题:

  <client>
    <endpoint address="http://localhost:8010/RouterService" binding="ws2007HttpBinding"
      bindingConfiguration="wsHttp"
      contract="localhost.IMessageManagerService" >
      <headers>
        <Route xmlns="http://www.thatindigogirl.com/samples/2008/01" >http://www.thatindigogirl.com/samples/2008/01/IMessageManagerService</Route>
      </headers>
    </endpoint>
  </client>

当可靠的会话被打开时,消息包含这个自定义头。
<Route a:IsReferenceParameter="true" xmlns="http://www.thatindigogirl.com/samples/2008/01">http://www.thatindigogirl.com/samples/2008/01/IMessageManagerService</Route>

这很好,但是我有一个要求需要通过编程来配置客户端。我想到ChannelFactory Endpoint应该有一个Header对象,我可以手动添加自定义标头。不幸的是它没有。所以我进行了一些搜索,并发现一些推荐实现IClientMessageInspector扩展WCF来添加我的标头,并将其作为行为添加到我的终结点。

public class ContractNameMessageInspector : IClientMessageInspector {

    private const string HEADER_NAME = "ContractName";
    private readonly string _ContractName;

    public ContractNameMessageInspector(string contractName) {
        _ContractName = contractName;
    }

    #region IClientMessageInspector Members

    public void AfterReceiveReply(ref Message reply, object correlationState) { }

    public object BeforeSendRequest(ref Message request, IClientChannel channel) {

        HttpRequestMessageProperty httpRequestMessage;
        object httpRequestMessageObject;

        if (request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out httpRequestMessageObject)) {
            httpRequestMessage = httpRequestMessageObject as HttpRequestMessageProperty;
            if (httpRequestMessage != null && string.IsNullOrEmpty(httpRequestMessage.Headers[HEADER_NAME])) {
                httpRequestMessage.Headers[HEADER_NAME] = this._ContractName;
            }
        }
        else {
            httpRequestMessage = new HttpRequestMessageProperty();
            httpRequestMessage.Headers.Add(HEADER_NAME, this._ContractName);
            request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestMessage);
        }
        return null;
    }

    #endregion
}

当我的客户端发起服务调用时,消息中包含自定义标头,但建立可靠会话的消息仍然不包含它。因此,我的问题是:如何以编程方式向终结点添加自定义标头,以便可靠会话消息包含它?感谢您的帮助。
3个回答

5

搞定了。虽然没有属性或方法可以向EndpointAddress添加标头,但构造函数有一个可选参数。

_Binding = bindingFactory.GetBinding(serviceUri, typeof(T));
AddressHeader header = AddressHeader.CreateAddressHeader("ContractName", "NameSpace", typeof (T).ToString());

_Address = new EndpointAddress(serviceUri, header);
_ChannelFactory = new ChannelFactory<T>(_Binding, _Address);

现在当我收到建立可靠会话的消息时,实际上它确实包含了我的自定义标头。这有些合理,因为消息检查器很可能只处理分派的消息,而建立可靠会话的消息是由更低级别的WCF代码生成的。


1

这对我有效

   public TResult Invoke<TResult>(Func<TClient, TResult> func,MessageHeader header)
    {
        TClient client = default(TClient);
        var sw = new Stopwatch();
        try
        {
            sw.Start();
            using (client = _channelFactory.CreateChannel())
            {
               using (OperationContextScope contextScope = new OperationContextScope(client))
                {
                    OperationContext.Current.OutgoingMessageHeaders.Add(header);

                    return func.Invoke(client);
                }
            }
        }
        finally
        {
            CloseConnection(client);
            Instrument(this.GetType().Name, sw);
        }
    }

0
要以编程方式添加地址头,请参阅MSDN的地址头,在那里可以以编程方式添加标题,例如:
var cl = new MyWCFClientContext();

var eab = new EndpointAddressBuilder(cl.Endpoint.Address);

eab.Headers.Add( AddressHeader.CreateAddressHeader("ClientIdentification", // Header Key
                                                    string.Empty,           // Namespace
                                                    "JabberwockyClient"));  // Header Value

cl.Endpoint.Address = eab.ToEndpointAddress();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接