ASP.NET MVC 5处理未授权请求

时间:2014-10-21 13:31:27

标签: c# asp.net asp.net-mvc asp.net-mvc-5

我正在尝试使用个人用户帐户身份验证模式在新的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 个答案:

答案 0 :(得分: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();
    }
}

注册并登录,尝试单击“关于”链接,您将被重定向到访问被拒绝的页面,因为没有具有角色的用户&#39; TestRole&#39;