MVC4 授权过滤器 AuthorizeAttribute

1.自定义授权特性,继承于AuthorizeAttribute

 /// <summary>
    /// 自定义授权特性,继承MVC授权过滤器,重写方法,运行时会自动验证有该特性的Action
    /// </summary>
    public class AuthenticationAttribute:System.Web.Mvc.AuthorizeAttribute
    {
        //重写授权方法
        public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
        {
             //验证是否有登录
        }    
MyAuthorizeAttribute

2.在MVC3 中就已经有全局过滤器特性,将自定义特性,添加到全局,会在访问所有的Action时,自动执行授权验证;

  如果不添加到全局过滤器,就只会对贴有自定义特性的类或是方法做授权验证

 1 public class FilterConfig
 2     {
 3         public static void RegisterGlobalFilters(GlobalFilterCollection filters)
 4         {
 5             filters.Add(new HandleErrorAttribute());
 6             //将授权验证添加为全局的 特性
 7             filters.Add(new AuthenticationAttribute());
 8 
 9         }
10     }
添加为全局过滤器

3.如果需要对某一些Action不做授权验证,可以在添加一个自定义特性,在授权过滤器中重写OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)时

  做判断;(主要是利用IsDefindAttribute方法做判断)

代码:

跳过特性:

1 /// <summary>
2     /// 跳过验证特性
3     /// </summary>
4     public class TakeValidateAttribute : Attribute
5     {
6 
7     }
跳过验证特性
1 //重写授权方法
2         public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
3         {
4            //1.验证是否登录
5             //判断被访问的Action是否有跳过验证特性
6             if (!IsDefindAttribute<TakeValidateAttribute>(filterContext.ActionDescriptor))
7             {
8 
9              }
判断是否有某一特性
原文地址:https://www.cnblogs.com/JsonYang/p/3591392.html