ASP.NET MVC 5 句柄被解除授权请求

发布时间: 2016/11/12 2:52:40
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我试图执行访问被拒绝错误页面上一个新的 ASP.NET MVC 5 项目与单个用户帐户的身份验证模式。 我添加 CustomAuthorize 从继承的类AuthorizeAttribute

public class CustomAuthorize : AuthorizeAttribute
{
    protected virtual CustomPrincipal CurrentUser
    {
        get { return HttpContext.Current.User as CustomPrincipal; }
    }

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAuthenticated)
        {
            if (!string.IsNullOrEmpty(Roles))
            {
                if (!CurrentUser.IsInRole(Roles))
                {
                    filterContext.Result = new RedirectToRouteResult(
                        new RouteValueDictionary(new { controller = "Error", action = "AccessDenied" }));

                    //base.OnAuthorization(filterContext); // returns to login url
                }
            }

            if (!string.IsNullOrEmpty(Users))
            {
                if (!Users.Contains(CurrentUser.UserName))
                {
                    filterContext.Result = new RedirectToRouteResult(
                        new RouteValueDictionary(new { controller = "Error", action = "AccessDenied" }));

                    //base.OnAuthorization(filterContext); // returns to login url
                }
            }
        }
    }


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

添加ErrorController.cs

public class ErrorController : Controller
{
    public ActionResult AccessDenied()
    {
        return View();
    }
}

AccessDenied.cshtml 视图

<h2>Access Denied</h2>
<p>You do not have access to view this page</p>

然后应用于HomeController.cs

[CustomAuthorize]
public class HomeController : Controller

但它总是重定向到登录页。如何显示访问被拒绝的页?

解决方法 1:

创建新 mvc 5 项目单独的用户帐户,添加你错误控制器、 视图和 CustomAuthorize 的属性类。

然后更新家居控制器像下面。

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [CustomAuthorize(Roles = "TestRole")]
    public ActionResult About()
    {
        ViewBag.Message = "Your application description page.";

        return View();
    }

    public ActionResult Contact()
    {
        ViewBag.Message = "Your contact page.";

        return View();
    }
}

注册和登录,试着点击链接你会得到重定向来访问被拒绝的页面,如没有用户与角色 '角色'

官方微信
官方QQ群
31647020