使用自定义属性处理未授权的

时间:2011-09-07 09:40:01

标签: asp.net-mvc asp.net-mvc-3 attributes custom-attributes

我有这个自定义授权类来检查用户是否是管理员:

public class IsAdminAttribute : AuthorizeAttribute
    {
        private datacontext() db = new datacontext();
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            var isAuthorized = base.AuthorizeCore(httpContext);
            if (isAuthorized)
            {
                var currentUser = httpContext.User.Identity.Name;
                return db.Users.Where(u => u.UserName == currentUser).Where(ut => ut.UserTypeID == 2).Count() == 1 ? true : false;
            }
            return isAuthorized;
        }

    }

并在此处使用:

[IsAdmin]
public ActionResult CreateUser()
{
    ViewBag.UserTypeID = new SelectList(db.UserTypes, "UserTypeId", "Name");
    return View();
}

并且工作正常但是当用户未获得授权时会将我带回登录页面。我想要发生的是将用户重定向到某处,并弹出错误消息。如何处理被拒绝的访问事件?

1 个答案:

答案 0 :(得分:7)

  

如何处理拒绝访问事件?

只需覆盖HandleUnauthorizedRequest方法并直接返回您喜欢的视图:

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
    filterContext.Result = new ViewResult
    {
        ViewName = "Unauthorized"
    };
}

这将呈现~/Views/Shared/Unauthorized.cshtml。您还可以将视图模型,母版页等传递给此ViewResult