mvc4 实现自己的权限验证 仿Authorize与AllowAnonymous原理

参考文章 :http://www.cosdiv.com/page/M0/S878/878978.html   

实现的效果:在控制器上(Controller)验证权限,在动作(Action)上不验证。

用MVC做网站的时候,想实现类似Authorize与AllowAnonymous功能,网上搜索了很久没找到原理,自己用反射查找方法上的特性,效果不太好,原来

MCV已经给我们做好了,

//用MVC系统自带的功能 获取当前方法上的特性名称
            bool skipAuthorization = filterContext.ActionDescriptor.IsDefined(typeof(NoNeedLogin), inherit: true)
                                     || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(NoNeedLogin), inherit: true);

如下是自己写的,好用:

IsLogin.cs

   public class IsLogin : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            bool isLogin = false;
            //用反射获取当前方法上的特性名称
            //Type t = this.GetType();
            //检查Action的特性有没有需要忽略登录检查的
            //string spaceName = "Web.Controllers";
            //string className = filterContext.RouteData.GetRequiredString("controller") + "Controller";
            //string methodName = filterContext.RouteData.GetRequiredString("action");
            //Type classType = Type.GetType(spaceName + "." + className);
            //MemberInfo memberInfo = classType.GetMethod(methodName,new Type[] { });
            //var atts = memberInfo.GetCustomAttributes(false);
            //foreach (Attribute att in atts)
            //{
            //    if (att.GetType().Name == "NoNeedLogin")
            //    {
            //        isLogin = true;
            //    }

            //}

            //用MVC系统自带的功能 获取当前方法上的特性名称
            bool skipAuthorization = filterContext.ActionDescriptor.IsDefined(typeof(NoNeedLogin), inherit: true)
                                     || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(NoNeedLogin), inherit: true);

            if (skipAuthorization)
            {
                return;
            }


            //检查是否登录
            AdminBll adminBll = new AdminBll();
            if (!adminBll.IsLogin())
            {
                filterContext.HttpContext.Response.Redirect("http://" + filterContext.HttpContext.Request.Url.Authority + "/Admin/Login");
            }



        }
    }

 

NoNeedLogin.cs

    public class NoNeedLogin : Attribute
    {

    }


AdminController.cs

    [IsLogin]
    public class AdminController : BaseController
    {

        #region Fields
        
        private INewsBll newsBll = new NewsBll();
        private INewsCategoryBll newsCatBll = new NewsCategoryBll();
        
        private IAdminBll adminBll = new AdminBll(); 
        #endregion



        // 后台管理首页 
        public ActionResult Index()
        {
            return View();
        }

        //登录 表单
        [NoNeedLogin]
        public ActionResult Login()
        {
            return View();
        }
}

 

这样就简单的实现了,在控制器上(Controller)验证权限,在动作(Action)上不验证的效果,还可以再优化一下。

 

posted @ 2013-09-10 15:54  中迁仙人  阅读(1814)  评论(0)    收藏  举报