ASP.NET MVC Authorization 自定义跳转

时间:2023-03-09 06:57:21
ASP.NET MVC Authorization 自定义跳转

应用场景:在 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 是在没有通过身份验证时执行。