WCF專題系列(4):深入WCF尋址Part 4—自定義消息篩選器

作者: TerryLee  來源: 博客園  發布時間: 2008-10-30 16:33  閱讀: 2417 次  推薦: 0   原文鏈接   [收藏]  
 

概述

WCF專題系列(3):深入WCF尋址Part 3—消息過濾引擎一文中,詳細介紹了WCF中的消息篩選引擎,包括消息篩選器和篩選器表,每個EndpointDispatcher都包含了兩個消息篩選器,默認的地址過濾器是EndpointAddressMessageFilter,默認的契約過濾器是ActionMessageFilter,這些是可以通過Behavior來改變的。本文我們將學習如何創建一個自定義的消息過濾器,并通過自定義Behavior來改變EndpointDispatcher的默認過濾器。

自定義過濾器

在默認情況下,默認情況下,僅當消息的“To”標頭為終結點的 EndpointAddress 并且消息的動作與終結點操作的動作之一匹配時,終結點的消息篩選器才與此消息匹配。在本文中,我們將自定義一個消息過濾器,它不要求消息的“To”標頭完全與EndpointAddress完全匹配,而只是檢測SOAP消息中的“To”標頭中是否包含某些特定的字符。所有的消息過濾器都從MessageFilter基類繼承,如下代碼所示:

/// <summary>
/// Author: TerryLee
/// Url: http://www.cnblogs.com/terrylee
/// </summary>
public class SpecialCharactersMessageFilter : MessageFilter
{
    private String _characters = String.Empty;

    public SpecialCharactersMessageFilter(string characters)
    {
        this._characters = characters;
    }

    public override bool Match(Message message)
    {
        Uri to = message.Headers.To;

        if (to == null)
            return false;

        return to.AbsoluteUri.Contains(_characters);
    }

    public override bool Match(MessageBuffer buffer)
    {
        return Match(buffer.CreateMessage());
    }
}

 

SpecialCharactersMessageFilter的實現非常簡單,僅僅是查找“To”標頭是否包含某些特定字符,這些字符我們會在配置文件中進行配置。

定義EndpointBehavior

現在我們自定義一個EndpointBehavior,使用它來替換EndpointDispatcher上的地址過濾器和契約過濾器,它實現自IendpointBehavior接口,如下代碼所示:

/// <summary>
/// Author: TerryLee
/// Url: http://www.cnblogs.com/terrylee
/// </summary>
public class FilteringEndpointBehavior : IEndpointBehavior
{
    MessageFilter addressFilter;
    MessageFilter contractFilter;

    public FilteringEndpointBehavior(MessageFilter addressFilter, 
        MessageFilter contractFilter)
    {
        this.addressFilter = addressFilter;
        this.contractFilter = contractFilter;
    }

    public void AddBindingParameters(ServiceEndpoint endpoint, 
        BindingParameterCollection bindingParameters)
    {
        
    }

    public void ApplyClientBehavior(ServiceEndpoint endpoint, 
        ClientRuntime clientRuntime)
    {
        throw new InvalidOperationException(
            "This behavior should only be used on the server.");
    }

    public void ApplyDispatchBehavior(ServiceEndpoint endpoint, 
        EndpointDispatcher endpointDispatcher)
    {
        endpointDispatcher.AddressFilter = this.addressFilter;
        endpointDispatcher.ContractFilter = this.contractFilter;
    }

    public void Validate(ServiceEndpoint endpoint)
    {
        
    }
}

 

這里只是實現了ApplyDispatchBehavior方法,其它方法暫時先不用考慮,另外,由于該Behavior只是用在服務端,所以在ApplyClientBehavior方法中拋出一個異常。

0
0
 
 
 

文章列表

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()