簡體   English   中英

OperationContextScope與MessageInpectors

[英]OperationContextScope vs MessageInpectors

幫助我理解兩者之間的差異。 對我來說,可以使用Operation ContextScope,而無論使用的是.NET應用程序(例如WCF,控制台,Web等)如何,如果調用任何其他服務(例如WCF或基於Java的服務),都可以在任何可用的.NET應用程序使用它。 [在ASMX服務的情況下可以正常工作]將標頭添加到傳出郵件中。

如果是這樣,那為什么我們在任何客戶端都需要MessageInspectors添加標頭? OperationContextScope比MessageInspectors簡單得多。 任何人都可以理解這兩者的正確用法嗎?

客戶端的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對於處理標頭(添加,刪除)很有用。

JuvalLöwy編寫的WCF服務編程附錄B很好地解釋了OperationContextScope。 Juval的框架ServiceModelEx有助於將OperationContextScopesGenericContext<T>類一起使用

請參閱Juval公司的網站以進行下載: http : //www.idesign.net/Downloads

問候

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM