如何将用户没有正确的角色重定向到Not Permitted?

时间:2013-07-16 15:27:50

标签: asp.net-mvc-4 simplemembership user-roles

在MVC 4项目中使用SimpleMembershipProvider时,如果没有正确角色的用户执行操作,则会将其重定向到Account / Login。如何将用户重定向到我自己的“没有足够的权限查看页面”操作?

1 个答案:

答案 0 :(得分:6)

您可以覆盖方法来执行此操作

public class CustomAuthorizeAttribute : AuthorizeAttribute {
    public override void OnAuthorization(AuthorizationContext filterContext) {
        base.OnAuthorization(filterContext);

        if (filterContext == null) {
            throw new ArgumentNullException("filterContext");
        }

        if ({your code detecting no user is logged}) {
            filterContext.Result = new RedirectResult(System.Web.Security.FormsAuthentication.LoginUrl + "?returnUrl=" + filterContext.HttpContext.Server.UrlEncode(filterContext.HttpContext.Request.RawUrl));
            return;
        }

        if ({your code detecting that the user has no access}) {
            var ViewData = new ViewDataDictionary();
            ViewData.Add("Title", "No access");
            ViewData.Add("Description", "blah blah blah blah blah blah blah ");
            filterContext.Result = new ViewResult { ViewName = "~/Views/Shared/NoAccess.cshtml", ViewData = ViewData };
        }

    }