ASP.NET MVC下判斷用戶登錄和授權狀態方法


在我們日常開發的絕大多數系統中,都涉及到管理用戶的登錄和授權問題。登錄功能(Authentication),針對於所有用戶都開放;而授權(Authorization),則對於某種用戶角色才開放。

在asp.net mvc中,微軟雖然已經幫助開發者構建了ASP.NET Identity這樣強大的驗證授權框架,但是如果想定制更多的邏輯功能的話,還得自己動動手。

根據日常的開發經驗,我總結了大概下面2種方法:

1、繼承Controller:

1.1 在我最早的時候,比較單純,也許是從WebForm那里學來的招式,我並沒有細讀Controller里的所有方法,所以在派生類里自己添加了驗證方法,然后在每個Action方法里調用。此方法現在看來有些蛋疼...

派生類如下:

public class AuthenticationControllor : Controller
{
    public bool Validate()
    {
        if (Session["username"] == null)
            return false;
        else
            return true;
    }

    public ActionResult RedirectLogin(bool redirect = true)
    {
        if (redirect)
            return RedirectToAction("Login", "Home", new { from = Request.Url.ToString() });
        else
            return RedirectToAction("Login", "Home");
    }
}

使用類如下:

public class HomeController : AuthenticationControllor
{
    public ActionResult Index()
    {
        if (!Validate())
            return RedirectLogin();
 
        return View();
    }
}

1.2 后來學習了很多人的代碼后,發現在Controller里有一個OnActionExecuting方法,此方法是在Action之前執行的,非常方便。

派生類如下:

public class AuthenticationControllor : Controller
{
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.HttpContext.Session["username"] == null)
            filterContext.Result = new RedirectToRouteResult("Login", new RouteValueDictionary { { "from", Request.Url.ToString() } });
            
        base.OnActionExecuting(filterContext);
    }
}

使用類如下:

// 不需要多寫任何邏輯代碼就能判斷是否登錄並跳轉
public class HomeController : AuthenticationControllor
{
    public ActionResult Index()
    { 
        return View();
    }
}

2. 繼承ActionFilterAttribute:

由於繼承Controller方法不太適合一個Controller下的有些Action需要登錄有些Action不需要登錄的場景,所以針對每個Action寫一個統一的特性會更好一些。

ActionFilterAttribute里也有OnActionExecuting方法,跟Controller一樣, 同是抽象實現了IActionFilter接口。

派生類如下:

// 登錄認證特性
public class AuthenticationAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.HttpContext.Session["username"] == null)
            filterContext.Result = new RedirectToRouteResult("Login", new RouteValueDictionary { { "from", Request.Url.ToString() } });
            
        base.OnActionExecuting(filterContext);
    }
}

使用方法如下:

public class HomeController : Controller 
{ 
    [Authentication] 
    public ActionResult Index()
    {
        return View();
    }
}

如果你想針對整個MVC項目的所有Action都使用此過濾器,步驟如下:

a. 確保Global.asax.cs的Application_Start方法中包含如下紅色行

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
    }
}

b. 在FilterConfig.cs文件中注冊相應的特性過濾器:

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
        filters.Add(new AuthenticationAttribute());
    }
}

 

推薦大家使用第2種過濾器的方法實現認證和授權。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM