2011-04-09 76 views
0

这是我的授权类,它覆盖了默认的AurthorizeCore,如果他没有授权,我想将用户重定向到错误页面。我怎么能做到这一点?如何重定向到一个视图从好友类asp.net MVC?

public class UserAcess : AuthorizeAttribute 
{ 
    private UserRepository _userRepo = new UserRepository(); 

    protected override bool AuthorizeCore(HttpContextBase httpContext) 
    { 

     var isAuthorized = base.AuthorizeCore(httpContext); 
     if (isAuthorized) 
     { 
      var canUse = this._userRepo.CanUserUseApp(httpContext.User.Identity.Name); 

      // If you can't use this app, guess what? ERROR PAGE fun times. 

      if (!canUse) 
      { 
       isAuthorized = false; 

       //redirect the user a view that I've made here. 
       return isAuthorized; 

      } 
     } 


     var personRole = this._userRepo.getPersonRolebyAdName(httpContext.User.Identity.Name); 


     //TODO Refactor this so that it checks if it's filled. 

     httpContext.Session["PersonID"] = personRole.Person.PersonID; 
     httpContext.Session["PersonRoleID"] = personRole.PersonRoleID; 
     httpContext.Session["UserName"] = personRole.Person.UserName; 
     httpContext.Session["Role"] = personRole.Role.Description; 
     httpContext.Session["FirstName"] = personRole.Person.FirstName; 
     httpContext.Session["LastName"] = personRole.Person.LastName; 

     return isAuthorized; 

    } 
} 

回答

3

你可以通过重写HandleUnauthorizedRequest方法做到这一点:

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) 
{ 
    filterContext.Result = new ViewResult 
    { 
     ViewName = "SomeUnauthorizedViewName" 
    }; 
} 
+0

再次感谢您达林!你很有帮助。我如何实际传递一个filterContext? – Gotjosh 2011-04-09 21:42:43

+0

@Gotjosh,什么'filterContext'?您只需将此方法覆盖到您的'UserAcess'类中。它会被自动调用。你不必打电话或传递任何东西。只要确保你已经指定了一个适当的路径来查看将要呈现的现有视图。 – 2011-04-09 21:44:35