mvc 4 ActionFilterAttribute 特性,进行权限验证

权限验证:

 /// <summary>
    /// 管理员身份验证
    /// </summary>
    public class BasicAuthenticationAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// 管理员信息
        /// </summary>
          public Admin Model { get; set; }
        /// <summary>
        /// 构造函数,进行获取管理员信息
        /// </summary>
          public BasicAuthenticationAttribute()
          { 
              string admininfo = CookieHelper.GetCookie("AdminInfo");
             
              if (!string.IsNullOrEmpty(admininfo))
              {
                  Model = MemcachedHelper.Get<Admin>(admininfo); 
              }
          }

         
        /// <summary>  
        /// 检查用户是否有该Action执行的操作权限  
        /// </summary>  
        /// <param name="actionContext"></param>  
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            ////在action执行前终止请求时,应该使用填充方法Response,将不返回action方法体。
          //  actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.OK,new{a=actionContext.ControllerContext.Request.RequestUri.LocalPath}); 
            //判断管理员是否存在
            if (Model == null)
            {
                if (!actionContext.ControllerContext.Request.RequestUri.LocalPath.ToLower().Equals("/api/login/login"))
                {
                     actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized); 
                } 
            }
            base.OnActionExecuting(actionContext); 
        }  
    }

BaseController

 [BasicAuthentication]
    public class BaseController : ApiController
    {
        /// <summary>
        /// 当前登录管理员信息
        /// </summary>
        public Admin AdminModel;
        public BaseController()
        {
            //通过反射获取验证特性中的属性
            Type tp = typeof(BaseController);
            MemberInfo info = tp;
            BasicAuthenticationAttribute basic = (BasicAuthenticationAttribute)Attribute.GetCustomAttribute(info, typeof(BasicAuthenticationAttribute));
            AdminModel = basic.Model;
        } 
    }

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。