我们知道在ASP.NET MVC中,在Action方法上应用ActionFilter过滤法时,它的执行流程如下图:
这个功能看起来很一般麽,可是实现功能的代码吊炸天(嘿嘿,要班门弄斧了,大神绕行吧!),卡忙北鼻...
由于在ASP.NET MVC中其功能涉及的代码太多,看起来太乱,下面就通过一个例子重点来介绍下这段吊爆的代码!
例子的环境是这样的:
1、有这么一个接口IFilterFunction,其中定义了两个方法!
1
2
3
4
5
6
|
public
interface
IFilterFunction
{
void
Before();
void
After();
}
|
2、一个方法!
1
2
3
4
5
|
public
string
ActionMethed()
{
Console.WriteLine(
"Action方法内容"
);
return
"Action"
;
}
|
需求来了,为了在执行ActionMethod方法的前后进行一些操作,要求实现功能:先执行所有实现了IFilterFunction接口的所有类的Before方法,再执行ActionMethed方法,然后再执行所有实现了IFilterFunction接口的所有类的After方法!(目的是在执行ActionMethod方法的前后进行一些操作)
对于这么一个需求,首先想到可以这么实现:
小吊实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
public
string
Start()
{
FilterOne filterOne =
new
FilterOne();
FilterTwo filterTwo =
new
FilterTwo();
FilterThree filterThree =
new
FilterThree();
filterThree.Before();
filterTwo.Before();
filterOne.Before();
string
str = ActionMethed();
filterOne.After();
filterTwo.After();
filterThree.After();
return
str;
}
|
虽然说可以实现,但是这么做有点太小儿科了,说好的吊爆呢?
来咯......
大吊实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
public
string
Start()
{
Func<
string
> continuation = () => ActionMethed();
List<IFilterFunction> lists =
new
List<IFilterFunction>();
lists.Add(
new
FilterOne());
lists.Add(
new
FilterTwo());
lists.Add(
new
FilterThree());
//就是它
Func<
string
> p = lists.Aggregate(continuation, (newcontinuation, filter) => () => Do(newcontinuation, filter));
return
p();
}
public
string
Do(Func<
string
> continuation, IFilterFunction filter)
{
filter.Before();
string
str = continuation();
filter.After();
return
str;
}
|
执行结果为:
没错,就是这么牛逼,利用累加器来一层一层的包装委托,之后执行委托,再一层一层的去执行。其过程如图:
ASP.NET MVC也就是使用这种方式来完成对Action方法和ActionFilter过滤器的执行。即:利用累加器来包装委托!
朋友,你能写出这样的代码吗? 实例源码下载
本文转自武沛齐博客园博客,原文链接:http://www.cnblogs.com/wupeiqi/p/3601104.html,如需转载请自行联系原作者