否认自定义角色

时间:2010-04-21 11:47:07

标签: asp.net-mvc authorization roles membership-provider

我怎样才能拒绝访问call方法。像这样的东西

    [HandleError]
    [Authorize(Roles = "role1, role2")]
    public class AdminController : Controller
    {          


        [Deny(Roles = "role2")]
        public ActionResult ResultPage(string message)
        {
            ViewData["message"] = message;
            return View();
        }
}

1 个答案:

答案 0 :(得分:4)

你可以简单地反过来检查是否存在role1而不是缺少role2。或者,您可以开发自己的DenyAttribute来执行您想要的操作,并验证用户是否处于指定角色。

[HandleError]
[Authorize(Roles = "role1, role2")]
public class AdminController : Controller
{          


    [Authorize(Roles = "role1")]
    public ActionResult ResultPage(string message)
    {
        ViewData["message"] = message;
        return View();
    }
}

public class DenyAttribute : AuthorizeAttribute
{

    protected override bool AuthorizeCore(HttpContextBase httpContext) {
        if (httpContext == null) {
            throw new ArgumentNullException("httpContext");
        }

        IPrincipal user = httpContext.User;
        if (!user.Identity.IsAuthenticated) {
            return false;
        }

        if (Users.Length > 0 && Users.Split(',').Any( u => string.Compare( u.Trim(), user.Identity.Name, StringComparer.OrdinalIgnoreCase))) {
            return false;
        }

        if (Roles.Length > 0 && Roles.Split(',').Any( u => user.IsInRole(u.Trim()))) {
            return false;
        }

        return true;
    }

}