ASP.Net MVC 3 Redirect UnAuthorized User not to loginUrl

前端 未结 6 1610
庸人自扰
庸人自扰 2020-12-23 22:40

i have a project using ASP.Net MVC3 and using membership for roles. i use authorize in every controller. eg:

[Authorize(Roles = \"Administrator\")]
    publ         


        
6条回答
  •  旧巷少年郎
    2020-12-23 23:07

    Just change the page that have to be shown in the web.config (check that the route exists)

    
      
    
    

    If you, instead, want to redirect to a specific path for every roles you can extend the AuthorizeAttribute with your own. Something like this (not tested, I write this to give you an idea)

    public class CheckAuthorize : ActionFilterAttribute
    {
      public Roles[] Roles { get; set; }
      public override void OnActionExecuting(ActionExecutingContext filterContext)
      {
        //Your code to get the user
        var user = ((ControllerBase)filterContext.Controller).GetUser();
    
        if (user != null)
        {
          foreach (Role role in Roles)
          {
            if (role == user.Role)
              return;
          }
        }      
        RouteValueDictionary redirectTargetDictionary = new RouteValueDictionary();
        if user.Role==Role.Administrator
        {
          redirectTargetDictionary.Add("action", "Unauthorized");
          redirectTargetDictionary.Add("controller", "Home");
        }
        else
        {
          redirectTargetDictionary.Add("action", "Logon");
          redirectTargetDictionary.Add("controller", "Home");
        }
        filterContext.Result = new RedirectToRouteResult(redirectTargetDictionary);
      }
    }
    

提交回复
热议问题