Fork me on GitHub

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

posted @ 2015-09-06 17:28  田园里的蟋蟀  阅读(1573)  评论(0编辑  收藏  举报