我正在使用MVC3,C#和Razor。
我正在尝试自定义Authorize属性。
代码段:
public class AuthorizeCustomAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var authorized = base.AuthorizeCore(httpContext);
if (!authorized)
{
// The user is not authenticated
return false;
}
var user = httpContext.User;
if (user.IsInRole("Admin")) // This should not be hardcoded, but use the Roles parm somehow. This is the core of my question here.
{
return true;
}
使用时,该属性如下所示:
[AuthorizeCustom(Roles="Admin,User")]
访问这个"角色"非常有用。参数及其在自定义属性类中的值,但我看不到如何做到这一点。 " httpContext"中必须有一个属性。变量,但它逃脱了我。
思想?
答案 0 :(得分:1)
语法:
[Authorize(Roles = "Admin,User")]
使用named parameter。这实际上是属性类中的属性。由于您的班级来自AuthorizeAttribute
,其中包含this property:
public string Roles { get; set; }
您应该能够在AuthorizeCustom
的构造函数中将其用作参数。