如何将“传递参数”添加到自定义AuthorizeAttribute

时间:2013-02-23 16:34:17

标签: c# asp.net-mvc asp.net-mvc-3 custom-attributes

我想保护控制器操作,以便只有角色为“Admin”的用户才能进入。
我根本没有使用角色/会员提供商。一切都是自定义的 到目前为止,我做到了这一点:

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var isAuthorized = base.AuthorizeCore(httpContext);            
        if (!isAuthorized)
            return false;

        string username = httpContext.User.Identity.Name;

        UserRepository repo = new UserRepository();

        return repo.IsUserInRole(username, "Admin");
    }
}

请注意,我在这里硬编码了“Admin” 我希望这是动态的 现在这项工作:

[CustomAuthorize]
        public ActionResult RestrictedArea()...

但我想要这样的事情:

[CustomAuthorize(Roles = "Admin")]
        public ActionResult RestrictedArea()

1 个答案:

答案 0 :(得分:20)

AuthorizeAttribute已有Roles属性,可用于此目的:

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var isAuthorized = base.AuthorizeCore(httpContext);            
        if (!isAuthorized)
        {
            return false;
        }

        string username = httpContext.User.Identity.Name;

        UserRepository repo = new UserRepository();

        return repo.IsUserInRole(username, this.Roles);
    }
}