您的位置:首页 > 编程语言 > ASP

ASP.NET MVC Authorization 自定义跳转

2015-09-06 17:28 507 查看
应用场景:在 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 是在没有通过身份验证时执行。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: