文章出處
文章列表
應用場景:在 ASP.NET MVC 應用程序中,需要對用戶身份權限進行驗證,比如沒有登錄或者不符合權限的用戶,訪問 Action 的時候,跳轉到指定頁面。
重寫 Authorize:
public class AdminAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (!httpContext.Request.IsAuthenticated)
{
return false;
}
else
{
if (!UserService.IsInRole(httpContext.User.Identity.Name, "admin"))
{
return false;
}
}
return true;
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new RedirectResult("http://www.sample.com");
}
}
Action 調用:
[AdminAuthorize]
public ActionResult Home()
{
return View();
}
注:HandleUnauthorizedRequest 是在沒有通過身份驗證時執行。
文章列表
全站熱搜