Net Mvc 統一登陸驗證

通過兩個自定義特性 ,實現統一登陸驗證。

1. 用於登陸NeedLoginAttribute;

 public class NeedLoginAttribute : ActionFilterAttribute
    {
        private static string _loginUrl = ConfigurationManager.AppSettings["LoginUrl"]?? "/Login";
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            
            //判斷Action方法的Control是否跳過登錄驗證
            if (filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(SkipCheckLoginAttribute), false))
            {
                return;
            }
            //判斷Action方法是否跳過登錄驗證
            if (filterContext.ActionDescriptor.IsDefined(typeof(SkipCheckLoginAttribute), false))
            {
                return;
            }
            if (true)
            {
                
                filterContext.HttpContext.Response.Redirect(_loginUrl);
                
            }
        }
    }

2. 免於登錄UnNeedLoginAttribute;

public class UnNeedLoginAttribute : System.Attribute
{
}

3. 使用方式。

1)創建baseController,所有的控制器繼承這個基類,這樣就可以在訪問action的時候先進行登陸驗證了;

[NeedLogin]
    public class BaseController : Controller
    {}

2)但是,但是存在登陸頁面的控制器繼承了基類,但是又不希望登陸,因爲本身不是登陸狀態,驗證登陸只會死循環。那麼該怎麼做呢?如下:

 [UnNeedCheckLogin]
    public class LoginController : BaseController
    {}

到此,MVC的統一登陸驗證就實現完畢!是不是很簡單。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章