MVC 受權過濾器簡單 實現

首先建立一個過濾器 MyAuthorizeAttribute 繼承AuthorizeAttribute,並重寫 AuthorizeCoreide

public class MyAuthorizeAttribute : AuthorizeAttribute
    {

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            string currentRole = httpContext.Request.Cookies["role"].Value;
            //從Session中獲取User對象,而後獲得其角色信息。若是用戶重寫了Identity, 則能夠在httpContext.Current.User.Identity中獲取  
            if (Roles.Contains(currentRole))
                return true;
            return base.AuthorizeCore(httpContext);
        }

    }

 

 

而後controler 引用過濾器code

[MyAuthorize(Roles = "Admin")]
        public ActionResult Index()
        {
            return Content("過濾器經過了");
        }

接下來再作一個受權不經過跳轉到登陸界面的:對象

   先重寫HandleUnauthorizedRequest繼承

/// <summary>
        /// 重寫過濾不過跳轉登陸界面
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            filterContext.HttpContext.Response.Redirect("/Home/Login");

            //base.HandleUnauthorizedRequest(filterContext);
        }
public ActionResult login()
        {
            return Content("這是登陸界面");
        }

相關文章
相關標籤/搜索