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

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-19
  • 2021-08-18
  • 2021-05-24
  • 2022-12-23
猜你喜欢
  • 2022-02-07
  • 2022-12-23
  • 2021-09-29
  • 2021-08-06
  • 2021-11-18
  • 2022-12-23
  • 2021-06-19
相关资源
相似解决方案