ASP.NET MVC和自定义授权属性

时间:2016-04-22 12:47:47

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

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

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

但是如何检查此属性中的User.Identity

2 个答案:

答案 0 :(得分:0)

您可以从以下位置访问它:

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

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