Asp.net mvc 4 ASP.NET MVC 4自定义授权属性-如何将未经授权的用户重定向到错误页面?

Asp.net mvc 4 ASP.NET MVC 4自定义授权属性-如何将未经授权的用户重定向到错误页面?,asp.net-mvc-4,authorization,custom-attributes,Asp.net Mvc 4,Authorization,Custom Attributes,我正在使用自定义的authorize属性根据用户的权限级别来授权用户的访问。我需要重定向未经授权的用户(例如,用户试图删除没有删除访问权限级别的发票)以访问拒绝页面 自定义属性正在工作。但在未经授权的用户访问的情况下,浏览器中不会显示任何内容 控制代码 public class InvoiceController : Controller { [AuthorizeUser(AccessLevel = "Create")] public ActionResult CreateNew

我正在使用自定义的authorize属性根据用户的权限级别来授权用户的访问。我需要重定向未经授权的用户(例如,用户试图删除没有删除访问权限级别的发票)以访问拒绝页面

自定义属性正在工作。但在未经授权的用户访问的情况下,浏览器中不会显示任何内容

控制代码

public class InvoiceController : Controller
{
    [AuthorizeUser(AccessLevel = "Create")]
    public ActionResult CreateNewInvoice()
    {
        //...

        return View();
    }

    [AuthorizeUser(AccessLevel = "Delete")]
    public ActionResult DeleteInvoice(...)
    {
        //...

        return View();
    }

    // more codes/ methods etc.
}
自定义属性类代码

public class AuthorizeUserAttribute : AuthorizeAttribute
{
    // Custom property
    public string AccessLevel { get; set; }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var isAuthorized = base.AuthorizeCore(httpContext);
        if (!isAuthorized)
        {                
            return false;
        }

        string privilegeLevels = string.Join("", GetUserRights(httpContext.User.Identity.Name.ToString())); // Call another method to get rights of the user from DB

        if (privilegeLevels.Contains(this.AccessLevel))
        {
            return true;
        }
        else
        {
            return false;
        }            
    }
}

如果你能分享你在这方面的经验,我将不胜感激

您必须按照指定覆盖
HandleUnauthorizedRequest


**注:2016年1月更新的条件语句可能重复。请参阅Ben Cull的答案,它解决了这个答案没有解决的线程安全问题。另外,应该是:if(false==filterContext.HttpContext.User.Identity.IsAuthenticated)如果重定向的目标操作采用了一个参数,您将如何将其传递给函数?例如:AcessDenied(需要字符串权限)
public class CustomAuthorize: AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if(!filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            base.HandleUnauthorizedRequest(filterContext);
        }
        else
        {
            filterContext.Result = new RedirectToRouteResult(new
            RouteValueDictionary(new{ controller = "Error", action = "AccessDenied" }));
        }
    }
}