我正在尝试创建自己的[Authorize]属性,因此我可以使用自己的授权逻辑来获得分层角色。
如果有人在控制器或操作上[Authorize(Roles = "Admin")]
如何在AuthorizeCore函数中获取字符串“Admin”?
我正在使用此代码:
public class Authorize : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
//authorize role logic
if (true)
return true;
return false;
}
}
MVC4,.net 4.5,c#,VS 2012
答案 0 :(得分:8)
这是你面临的常见问题。
post中的这个建议应该适用于MVC4,因为它在MVC 3中工作: - ASP.NET MVC - Alternative to Role Provider?
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
bool isAdmin;
if(Roles.Contains("Admin"))
isAdmin = true;
return isAdmin ;
}
答案 1 :(得分:1)
角色是公共财产。你应该能够做到这一点:
public class Authorize : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if(Roles.Contains("MyRole"))
return true;
return false;
}
}
或者你需要做什么
答案 2 :(得分:0)
如果您需要获取允许的角色列表,您只需获取Roles属性即可。它将列出属性修饰中指定的字符串。
public class Authorize : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var allowedRoles = Roles;
}
}
上看到这一点