【问题标题】:Handling the not authorized using custom attributes使用自定义属性处理未授权
【发布时间】:2011-11-12 00:02:09
【问题描述】:

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

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();
}

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

【问题讨论】:

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


    【解决方案1】:

    如何处理拒绝访问事件?

    只需重写HandleUnauthorizedRequest方法,直接返回你喜欢的视图:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-01
      • 2014-10-28
      • 1970-01-01
      • 2015-03-03
      • 1970-01-01
      相关资源
      最近更新 更多