如何在自定义授权属性时使用“角色”参数

3

我正在使用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")]

获取“Roles”参数及其值对于自定义属性类非常有用,但我不知道如何实现。在“httpContext”变量中必须有一个属性,但我无法找到它。
你有什么想法吗?
1个回答

1

的语法是:

[Authorize(Roles = "Admin,User")]

使用命名参数。实际上,它是属性类的属性。由于你的类派生自AuthorizeAttribute,其中包含这个属性

public string Roles { get; set; }

您应该能够将其作为AuthorizeCustom构造函数的参数使用。


我需要专门测试这个Roles属性吗?还是这发生在基类中,因此有一个可以调用的结果属性,比如RolesValid?我没有看到任何东西,所以我推测我需要做 "if IsInRoles(Roles) {return true}"。 - undefined
我认为它会自动包含在 "base.AuthorizeCore(httpContext)" 中吗? - undefined
是的,没错,刚刚确认了 :) - undefined
是的,authorize方法会考虑角色。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接