.NET MVC中的过滤器

过滤器其实就是.net中的特性,在.net.35之后我们可以在类或者方法名称上面加某种特性,而在.net mvc环境下,有几个比较重要的特性,如AuthorizeAttribute

它主要有在权限验证上,有时我们习惯叫它“过滤器”,原因是它可以把不符合要求的用户过滤掉,呵呵,下面是系统中常见的用户权限过滤器的代码,供大家学习

 1 namespace Web.Attributes
 2 {
 3 
 4     /// <summary>
 5     /// 用户验证列举
 6     /// </summary>
 7     public enum AuthenticationType
 8     {
 9         /// <summary>
10         /// 登录
11         /// </summary>
12         Login,
13         /// <summary>
14         /// 后台登陆
15         /// </summary>
16         BackgroundLogin,
17         /// <summary>
18         /// 注册
19         /// </summary>
20         Register,
21     }
22 
23     /// <summary>
24     /// 用户验证过滤器:前台
25     /// </summary>
26     public class UserAuthentication : AuthorizeAttribute
27     {
28         public AuthenticationType Authentication { get; set; }
29         /// <summary>
30         /// 构造函数
31         /// </summary>
32         public UserAuthentication()
33             : this(AuthenticationType.Login) { }
34         public UserAuthentication(AuthenticationType authentication)
35         {
36             this.Authentication = authentication;
37         }
38         /// <summary>
39         /// 执行前验证
40         /// </summary>
41         public override void OnAuthorization(AuthorizationContext filterContext)
42         {
43 
44             //验证不成功的时候
45             switch (this.Authentication)
46             {
47                 case AuthenticationType.Login:
48                     if (!ClientHelper.Current.HasUserInfo)
49                         filterContext.Result = new RedirectToRouteResult("Default", new RouteValueDictionary { { "Action", "LogOn" }, { "Controller", "Account" }, { "returnUrl", HttpContext.Current.Request.Url.ToString() } });
50                     break;
51 
52                 case AuthenticationType.BackgroundLogin:
53                     if (string.IsNullOrEmpty(SessionAction.ReadSession("Background_Current_UserID")) || Convert.ToInt32(SessionAction.ReadSession("Background_Current_UserID")) < 0)
54                         filterContext.Result = new RedirectToRouteResult("Default", new RouteValueDictionary { { "Action", "LogOn" }, { "Controller", "Account" }, { "returnUrl", HttpContext.Current.Request.Url.ToString() } });
55                     break;
56                 case AuthenticationType.Register:
57                     filterContext.Result = new RedirectToRouteResult("Default", new RouteValueDictionary { { "Action", "Register" }, { "Controller", "Account" } });
58                     break;
59                 default:
60                     filterContext.Result = new RedirectToRouteResult("Default", new RouteValueDictionary { { "Action", "Index" }, { "Controller", "Home" } });
61                     break;
62             }
63 
64         }
65     }
66 }
本文转自博客园张占岭(仓储大叔)的博客,原文链接:.NET MVC中的过滤器,如需转载请自行联系原博主。
上一篇:Secret Message 秘密信息【Trie】


下一篇:模仿android网易新闻客户端左右动画效果