您好,欢迎访问一九零五行业门户网

[ASP.NET MVC 小牛之路]11 - Filter

[asp.net
mvc 小牛之路]11 - filter
filter(筛选器)是基于aop(面向方面编程)的设计,它的作用是对mvc框架处理客户端请求注入额外的逻辑,以非常简单优美的方式实现横切关注点(cross-cutting concerns)。横切关注点是指横越应该程序的多个甚至所有模块的功能,经典的横切关注点有日志记录、缓存处理、异常处理和权限验证等。本文将分别介绍mvc框架所支持的不同种类的filter的创建和使用,以及如何控制它们的执行。
本文目录
四种基本 filter 概述
mvc框架支持的filter可以归为四类,每一类都可以对处理请求的不同时间点引入额外的逻辑处理。这四类filter如下表:
在mvc框架调用acion之前,它会先判断有没有实现上表中的接口的特性,如果有,则在请求管道的适当的点调用特性中定义的方法。
mvc框架为这些种类的filter接口实现了默认的特性类。如上表,actionfilterattribute 类实现了 iactionfilter 和 iresultfilter 两个接口,这个类是一个抽象类,必须对它提供实现。另外两个特性类,authorizeattribute 和 handleerrorattribute, 已经提供了一些有用的方法,可以直接使用。
filter 既能应用在单个的ation方法上,也能应用在整个controller上,并可以在acion和controller上应用多个filter。如下所示:
[authorize(roles="trader")] // 对所有action有效 public class examplecontroller : controller { [showmessage] // 对当前ation有效 [outputcache(duration=60)] // 对当前ation有效 public actionresult index() { // ... } }
注意,对于自定义的controller的基类,应用于该基类的filter也将对继承自该基类的所有子类有效。
authorization filter
authorization filter是在action方法和其他种类的filter之前运行的。它的作用是强制实施权限策略,保证action方法只能被授权的用户调用。authorization filter实现的接口如下:
namespace system.web.mvc { public interface iauthorizationfilter { void onauthorization(authorizationcontext filtercontext); } }
自定义authorization filter
你可以自己实现 iauthorizationfilter 接口来创建自己的安全认证逻辑,但一般没有这个必要也不推荐这样做。如果要自定义安全认证策略,更安全的方式是继承默认的 authorizeattribute 类。
我们下面通过继承 authorizeattribute 类来演示自定义authorization filter。新建一个空mvc应用程序,和往常的示例一样添加一个 infrastructure 文件夹,然后添加一个 customauthattribute.cs 类文件,代码如下:
namespace mvcapplication1.infrastructure { public class customauthattribute : authorizeattribute { private bool localallowed; public customauthattribute(bool allowedparam) { localallowed = allowedparam; } protected override bool authorizecore(httpcontextbase httpcontext) { if (httpcontext.request.islocal) { return localallowed; } else { return true; } } } }
这个简单的filter,通过重写 authorizecore 方法,允许我们阻止本地的请求,在应用该filter时,可以通过构造函数来指定是否允许本地请求。authorizeattribte 类帮我们内置地实现了很多东西,我们只需把重点放在 authorizecore 方法上,在该方法中实现权限认证的逻辑。
为了演示这个filter的作用,我们新建一个名为 home 的 controller,然后在 index action方法上应用这个filter。参数设置为false以保护这个 action 不被本地访问,如下:
public class homecontroller : controller { [customauth(false)] public string index() { return "this is the index action on the home controller"; } }
运行程序,根据系统生成的默认路由值,将请求 /home/index,结果如下:
我们通过把 authorizeattribute 类作为基类自定义了一个简单的filter,那么 authorizeattribute 类本身作为filter有哪些有用的功能呢?
使用内置的authorization filter
当我们直接使用 authorizeattribute 类作为filter时,可以通过两个属性来指定我们的权限策略。这两个属性及说明如下:
users属性,string类型,指定允许访问action方法的用户名,多个用户名用逗号隔开。
roles属性,string类型,用逗号分隔的角色名,访问action方法的用户必须属于这些角色之一。
使用如下:
public class homecontroller : controller { [authorize(users = "jim, steve, jack", roles = "admin")] public string index() { return "this is the index action on the home controller"; } }
这里我们为index方法应用了authorize特性,并同时指定了能访问该方法的用户和角色。要访问index action,必须两者都满足条件,即用户名必须是 jim, steve, jack 中的一个,而且必须属性 admin 角色。
另外,如果不指定任何用户名和角色名(即 [authorize] ),那么只要是登录用户都能访问该action方法。
你可以通过创建一个internet模板的应用程序来看一下效果,这里就不演示了。
对于大部分应用程序,authorizeattribute 特性类提供的权限策略是足够用的。如果你有特殊的需求,则可以通过继承authorizeattribute 类来满足。
exception filter
exception filter,在下面三种来源抛出未处理的异常时运行:
另外一种filter(如authorization、action或result等filter)。
action方法本身。
action方法执行完成(即处理actionresult的时候)。
exception filter必须实现 iexceptionfilter 接口,该接口的定义如下:
namespace system.web.mvc { public interface iexceptionfilter { void onexception(exceptioncontext filtercontext); } }
exceptioncontext 常用属性说明
在 iexceptionfilter 的接口定义中,唯一的 onexception 方法在未处理的异常引发时执行,其中参数的类型:exceptioncontext,它继承自 controllercontext 类,controllercontext 包含如下常用的属性:
controller,返回当前请求的controller对象。
httpcontext,提供请求和响应的详细信息。
ischildaction,如果是子action则返回true(稍后将简单介绍子action)。
requestcontext,提供请求上下文信息。
routedata,当前请求的路由实例信息。
作为继承 controllercontext 类的子类,exceptioncontext 类还提供了以下对处理异常的常用属性:
actiondescriptor,提供action方法的详细信息。
result,是一个 actionresult 类型,通过把这个属性值设为非空可以让某个filter的执行取消。
exception,未处理异常信息。
exceptionhandled,如果另外一个filter把这个异常标记为已处理则返回true。
一个exception filter可以通过把 exceptionhandled 属性设置为true来标注该异常已被处理过,这个属性一般在某个action方法上应用了多个exception filter时会用到。exceptionhandled 属性设置为true后,就可以通过该属性的值来判断其它应用在同一个action方法exception filter是否已经处理了这个异常,以免同一个异常在不同的filter中重复被处理。
示例演示
在 infrastructure 文件夹下添加一个 rangeexceptionattribute.cs 类文件,代码如下:
public class rangeexceptionattribute : filterattribute, iexceptionfilter { public void onexception(exceptioncontext filtercontext) { if (!filtercontext.exceptionhandled && filtercontext.exception is argumentoutofrangeexception) { filtercontext.result = new redirectresult("~/content/rangeerrorpage.html"); filtercontext.exceptionhandled = true; } } }
这个exception filter通过重定向到content目录下的一个静态html文件来显示友好的 argumentoutofrangeexception 异常信息。我们定义的 rangeexceptionattribute 类继承了filterattribute类,并且实现了iexception接口。作为一个mvc filter,它的类必须实现imvcfilter接口,你可以直接实现这个接口,但更简单的方法是继承 filterattribute 基类,该基类实现了一些必要的接口并提供了一些有用的基本特性,比如按照默认的顺序来处理filter。
在content文件夹下面添加一个名为rangeerrorpage.html的文件用来显示友好的错误信息。如下所示:
<!doctype html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>range error</title> </head> <body> <h2>sorry</h2> <span>one of the arguments was out of the expected range.</span> </body> </html>
在homecontroller中添加一个值越限时抛出异常的action,如下所示:
public class homecontroller : controller { [rangeexception] public string rangetest(int id) { if (id > 100) { return string.format("the id value is: {0}", id); } else { throw new argumentoutofrangeexception("id", id, ""); } } }
当对rangetest应用自定义的的exception filter时,运行程序url请求为 /home/rangetest/50,程序抛出异常后将重定向到rangeerrorpage.html页面:
由于静态的html文件是和后台脱离的,所以实际项目中更多的是用一个view来呈现友好的错误信息,以便很好的对它进行一些动态的控制。如下面把示例改动一下,rangeexceptionattribute 类修改如下:
public class rangeexceptionattribute : filterattribute, iexceptionfilter { public void onexception(exceptioncontext filtercontext) { if (!filtercontext.exceptionhandled && filtercontext.exception is argumentoutofrangeexception) { int val = (int)(((argumentoutofrangeexception)filtercontext.exception).actualvalue); filtercontext.result = new viewresult { viewname = "rangeerror", viewdata = new viewdatadictionary<int>(val) }; filtercontext.exceptionhandled = true; } } }
我们创建一个viewresult对象,指定了发生异常时要重定向的view名称和传递的model对象。然后我们在views/shared文件夹下添加一个rangeerror.cshtml文件,代码如下:
@model int <!doctype html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>range error</title> </head> <body> <h2>sorry</h2> <span>the value @model was out of the expected range.</span> <div> @html.actionlink("change value and try again", "index") </div> </body> </html>
运行结果如下:
禁用异常跟踪
很多时候异常是不可预料的,在每个action方法或controller上应用exception filter是不现实的。而且如果异常出现在view中也无法应用filter。如rangeerror.cshtml这个view加入下面代码:
@model int @{ var count = 0; var number = model / count; } ...
运行程序后,将会显示如下信息:
显然程序发布后不应该显示这些信息给用户看。我们可以通过配置web.config让应用程序不管在何时何地引发了异常都可以显示统一的友好错误信息。在web.config文件中的<system.web>节点下添加如下子节点:
<system.web> ... <customerrors mode="on" defaultredirect="/content/rangeerrorpage.html"/> </system.web>
这个配置只对远程访问有效,本地运行站点依然会显示跟踪信息。
使用内置的 exceptin filter
通过上面的演示,我们理解了exceptin filter在mvc背后是如何运行的。但我们并不会经常去创建自己的exceptin filter,因为微软在mvc框架中内置的 handleerrorattribute(实现了iexceptionfilter接口) 已经足够我们平时使用。它包含exceptiontype、view和master三个属性。当exceptiontype属性指定类型的异常被引发时,这个filter将用view属性指定的view(使用默认的layout或mast属性指定的layout)来呈现一个页面。如下面代码所示:
... [handleerror(exceptiontype = typeof(argumentoutofrangeexception), view = "rangeerror")] public string rangetest(int id) { if (id > 100) { return string.format("the id value is: {0}", id); } else { throw new argumentoutofrangeexception("id", id, ""); } } ...
使用内置的handleerrorattribute,将异常信息呈现到view时,这个特性同时会传递一个handleerrorinfo对象作为view的model。handleerrorinfo类包含actionname、controllername和exception属性,如下面的 rangeerror.cshtml 使用这个model来呈现信息:
@model handleerrorinfo @{ viewbag.title = "sorry, there was a problem!"; } <!doctype html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>range error</title> </head> <body> <h2>sorry</h2> <span>the value @(((argumentoutofrangeexception)model.exception).actualvalue) was out of the expected range.</span> <div> @html.actionlink("change value and try again", "index") </div> <div style="display: none"> @model.exception.stacktrace </div> </body> </html>
action filter
顾名思义,action filter是对action方法的执行进行“筛选”的,包括执行前和执行后。它需要实现 iactionfilter 接口,该接口定义如下:
namespace system.web.mvc { public interface iactionfilter { void onactionexecuting(actionexecutingcontext filtercontext); void onactionexecuted(actionexecutedcontext filtercontext); } }
其中,onactionexecuting方法在action方法执行之前被调用,onactionexecuted方法在action方法执行之后被调用。我们来看一个简单的例子。
在infrastructure文件夹下添加一个profileactionattribute类,代码如下:
using system.diagnostics; using system.web.mvc; namespace mvcapplication1.infrastructure { public class profileactionattribute : filterattribute, iactionfilter { private stopwatch timer; public void onactionexecuting(actionexecutingcontext filtercontext) { timer = stopwatch.startnew(); } public void onactionexecuted(actionexecutedcontext filtercontext) { timer.stop(); if (filtercontext.exception == null) { filtercontext.httpcontext.response.write( string.format("<div>action method elapsed time: {0}</div>", timer.elapsed.totalseconds)); } } } }
在homecontroller中添加一个action并应用该filter,如下:
... [profileaction] public string filtertest() { return "this is the actionfiltertest action"; } ...
运行程序,url定位到/home/filtertest,结果如下:
我们看到,profileaction的 onactionexecuted 方法是在 filtertest 方法返回结果之前执行的。确切的说,onactionexecuted 方法是在action方法执行结束之后和处理action返回结果之前执行的。
onactionexecuting方法和onactionexecuted方法分别接受actionexecutingcontext和actionexecutedcontext对象参数,这两个参数包含了actiondescriptor、canceled、exception等常用属性。
result filter
result filter用来处理action方法返回的结果。用法和action filter类似,它需要实现 iresultfilter 接口,定义如下:
namespace system.web.mvc { public interface iresultfilter { void onresultexecuting(resultexecutingcontext filtercontext); void onresultexecuted(resultexecutedcontext filtercontext); } }
iresultfilter 接口和之前的 iactionfilter 接口类似,要注意的是result filter是在action filter之后执行的。两者用法是一样的,不再多讲,直接给出示例代码。
在infrastructure文件夹下再添加一个 profileresultattribute.cs 类文件,代码如下:
public class profileresultattribute : filterattribute, iresultfilter { private stopwatch timer; public void onresultexecuting(resultexecutingcontext filtercontext) { timer = stopwatch.startnew(); } public void onresultexecuted(resultexecutedcontext filtercontext) { timer.stop(); filtercontext.httpcontext.response.write( string.format("<div>result elapsed time: {0}</div>", timer.elapsed.totalseconds)); } }
应用该filter:
... [profileaction] [profileresult] public string filtertest() { return "this is the actionfiltertest action"; } ...
内置的 action 和 result filter
mvc框架内置了一个 actionfilterattribute 类用来创建action 和 result 筛选器,即可以控制action方法的执行也可以控制处理action方法返回结果。它是一个抽象类,定义如下:
public abstract class actionfilterattribute : filterattribute, iactionfilter, iresultfilter{ public virtual void onactionexecuting(actionexecutingcontext filtercontext) { } public virtual void onactionexecuted(actionexecutedcontext filtercontext) { } public virtual void onresultexecuting(resultexecutingcontext filtercontext) { } public virtual void onresultexecuted(resultexecutedcontext filtercontext) { } } }
使用这个抽象类方便之处是你只需要实现需要加以处理的方法。其他和使用 iactionfilter 和 iresultfilter 接口没什么不同。下面是简单做个示例。
在infrastructure文件夹下添加一个 profileallattribute.cs 类文件,代码如下:
public class profileallattribute : actionfilterattribute { private stopwatch timer; public override void onactionexecuting(actionexecutingcontext filtercontext) { timer = stopwatch.startnew(); } public override void onresultexecuted(resultexecutedcontext filtercontext) { timer.stop(); filtercontext.httpcontext.response.write( string.format("<div>total elapsed time: {0}</div>", timer.elapsed.totalseconds)); } }
在homecontroller中的filtertest方法上应用该filter:
... [profileaction] [profileresult] [profileall] public string filtertest() { return "this is the filtertest action"; } ...
运行程序,url定位到/home/filtertest,可以看到一个action从执行之前到结果处理完毕总共花的时间:
我们也可以controller中直接重写 actionfilterattribute 抽象类中定义的四个方法,效果和使用filter是一样的,例如:
public class homecontroller : controller { private stopwatch timer; ... public string filtertest() { return "this is the filtertest action"; } protected override void onactionexecuting(actionexecutingcontext filtercontext) { timer = stopwatch.startnew(); } protected override void onresultexecuted(resultexecutedcontext filtercontext) { timer.stop(); filtercontext.httpcontext.response.write( string.format("<div>total elapsed time: {0}</div>", timer.elapsed.totalseconds)); }
注册为全局 filter
全局filter对整个应用程序的所有controller下的所有action方法有效。在app_start/filterconfig.cs文件中的registerglobalfilters方法,可以把一个filter类注册为全局,如:
using system.web; using system.web.mvc; using mvcapplication1.infrastructure; namespace mvcapplication1 { public class filterconfig { public static void registerglobalfilters(globalfiltercollection filters) { filters.add(new handleerrorattribute()); filters.add(new profileallattribute()); } } }
我们增加了filters.add(new profileallattribute())这行代码,其中的filters参数是一个globalfiltercollection类型的集合。为了验证 profileallattribute 应用到了所有action,我们另外新建一个controller并添加一个简单的action,如下:
public class customercontroller : controller { public string index() { return "this is the customer controller"; } }
运行程序,将url定位到 /customer ,结果如下:
其它常用 filter
mvc框架内置了很多filter,常见的有requirehttps、outputcache、asynctimeout等等。下面例举几个常用的。
requirehttps,强制使用https协议访问。它将浏览器的请求重定向到相同的controller和action,并加上 https:// 前缀。
outputcache,将action方法的输出内容进行缓存。
asynctimeout/noasynctimeout,用于异步controller的超时设置。(异步controller的内容请访问 xxxxxxxxxxxxxxxxxxxxxxxxxxx)
childactiononlyattribute,使用action方法仅能被html.action和html.renderaction方法访问。
这里我们选择 outputcache 这个filter来做个示例。新建一个 selectivecache controller,代码如下:
public class selectivecachecontroller : controller { public actionresult index() { response.write("action method is running: " + datetime.now); return view(); } [outputcache(duration = 30)] public actionresult childaction() { response.write("child action method is running: " + datetime.now); return view(); } }
这里的 childaction 应用了 outputcache filter,这个action将在view内被调用,它的父action是index。
现在我们分别创建两个view,一个是childaction.cshtml,代码如下:
@{ layout = null; } <h4>this is the child action view</h4>
另一个是它的index.cshtml,代码如下:
@{ viewbag.title = "index"; } <h2>this is the main action view</h2> @html.action("childaction")
运行程序,将url定位到 /selectivecache ,过几秒刷新一下,可看到如下结果:
以上就是[asp.net mvc 小牛之路]11 - filter的内容。
其它类似信息

推荐信息