您的位置:知识库 »

WCF专题系列(4):深入WCF寻址Part 4—自定义消息筛选器

作者: TerryLee  来源: 博客园  发布时间: 2008-10-30 16:33  阅读: 2538 次  推荐: 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
 

热门文章

    最新文章

      最新新闻

        热门新闻