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

参见英文答案 > ASP.NET MVC – How to show unauthorized error on login page?7个答案我正在使用自定义授权属性来授权用户根据权限级别进行访问。我需要重定向未经授权的用户(例如,用户尝试删除没有删除访问级别的发票)来访问被拒绝的页面

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

Contoller代码

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

感谢您能分享您的经验。

解决方法

您必须按照 here规定覆盖HandleUnauthorizedRequest。
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" }));
}
}
}

**注意:更新的条件语句Jan ’16

相关文章

这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识...
Some samples are below for ASP.Net web form controls:(fr...
问题描述: 对于未定义为 System.String 的列,唯一有效的值...
最近用到了CalendarExtender,结果不知道为什么发生了错位,...
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence cha...