1

帮助我理解这两者之间的差异。根据我的说法,无论您使用什么 .NET 应用程序(如 WCF、控制台、Web 等),都可以使用 Operation ContextScope,如果您正在调用任何其他服务(如 WCF 或基于 Java 的服务),则可以在任何地方使用它[这不会在 ASMX 服务的情况下工作]将标头添加到传出消息中。

如果是这样,那么为什么我们需要在任何客户端添加 MessageInspectors 来添加标头?OperationContextScope 比 MessageInspector 简单得多。有人阐明了这两个的正确用法吗?

4

1 回答 1

1

IClientMessageInspector在客户端和IDispatchMessageInspector服务器端都擅长检查消息体,可能会在发送之前修改消息,或者修改接收到的内容。

这是一个示例:

public class MyMessageInspector : IClientMessageInspector
{
    public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
    { 
        // Inspect and/or modify the message here
        MessageBuffer mb = reply.CreateBufferedCopy(int.MaxValue);
        Message newMsg = mb.CreateMessage();

        var reader = newMsg.GetReaderAtBodyContents().ReadSubtree();
        XElement bodyElm = XElement.Load(reader);
        // ...
        reply = newMsg;
    }
    public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel)
    {
        // Something could be done here
        return null;
    }
}

编写一个行为以轻松地将检查器应用于客户端:

public class MyInspectorBehavior : IEndpointBehavior
{
    #region IEndpointBehavior Members
    public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
    {
        clientRuntime.MessageInspectors.Add(
            new MyMessageInspector()
            );
    }

    public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
    {}
    public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
    {}
    public void Validate(ServiceEndpoint endpoint)
    {}
    #endregion
}

使用行为:

        ChannelFactory<IService1> cf = 
            new ChannelFactory<IService1>(
                new BasicHttpBinding(),
                "http://localhost:8734/DataService.svc");

        cf.Endpoint.Behaviors.Add(
            new MyInspectorBehavior()
            );

使用 IDispatcherMessageInspector 在服务器端也可以做同样的事情。
该行为可以使用 C#、XML (app.config/web.config) 或以声明方式放在服务实现中:

[MyServiceInspectorBehavior]
public class ServiceImpl : IService1
{ ...}

OperationContextScope 对于处理标头(添加、删除)很有用。

来自 Juval Löwy 的 Programming WCF Services,附录 B 很好地解释了 OperationContextScope。Juval 的框架,ServiceModelEx 帮助OperationContextScopesGenericContext<T>类一起使用

请参阅 Juval 的公司网站进行下载:http ://www.idesign.net/Downloads

问候

于 2015-09-28T12:47:36.943 回答