2016-04-22 140 views
0

我在我的ASP.NET MVC控制器中使用[Authorize][Authorize(Roles = "User")]属性,所以当我不在“用户”角色[Authorize(Roles = "User")]重定向到登录页面。现在网站有大约10个不同的角色,我需要重定向到不同的页面。我对这个想法是写自己的AttributeASP.NET MVC和自定义授权属性

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method, AllowMultiple = true)] 
public class CustomAuthorize : FilterAttribute 
{ 
    public CustomAuthorize(string role) 
    { 
     ...    
    } 
} 

但我怎么能在这个属性检查User.Identity

回答

0

您可以访问它:

System.Web.HttpContext.Current.Identity.Name; 
0

如果你想使用一个过滤器,你可以使用OnActionExecuting()方法,这将提供一个filterContext参数可以用来解决您的当前用户:

public class CustomAuthorize : ActionFilterAttribute, IActionFilter 
{ 
    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     // Use the context to access the user 
     var user = filterContext.HttpContext.User; 

     if(user != null) 
     { 
      // Check your role and redirect accordingly here 
      var roles = Roles.GetRolesForUser(user.Identity.Name); 

      // Grab the first role (example) 
      var role = roles.FirstOrDefault(); 

      // Based on the users role, do something 
      switch(role) 
      { 
       case "Administrator": 
         // Handle your redirect here 
         filterContext.Result = new RedirectToRouteResult("Admin", routeValues); 
       break; 
       default: 
         // Do nothing, allow to pass through as usual 
       break; 
      } 
     } 
     base.OnActionExecuting(filterContext); 
    } 
} 

同样,你可以让你的CustomAuthorize类继承的基础AuthorizeAttribute,那么你可以使用的方法AuthorizeCore()被暴露已经有一个参数为当前上下文来处理做什么:

public class CustomAuthorize : AuthorizeAttribute 
{ 
    protected override bool AuthorizeCore(HttpContextBase httpContext) 
    { 
     // Access your current user from the context 
     var user = httpContext.User; 

     // Do stuff here 


     return base.AuthorizeCore(httpContext); 
    } 
}