开发者

Handling the not authorized using custom attributes

I have this custom authorization class to check if a user is an admin:

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

    }

and is used here:

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

and works ok but takes me back to my log in page when the user is not authorized. What I want to happen is for the user to be redirected somewhere with an error message p开发者_如何学运维opping up. How do I handle the denied access event?


How do I handle the denied access event?

Simply override the HandleUnauthorizedRequest method and return directly the view you like:

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

This will render ~/Views/Shared/Unauthorized.cshtml. You could also pass view models, master pages, etc... to this ViewResult.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜