【问题标题】:How can I use the "Roles" parameter when Customising the Authorize Attribute自定义授权属性时如何使用“角色”参数
【发布时间】:2014-03-23 17:05:40
【问题描述】:

我正在使用 MVC3、C# 和 Razor。

我正在尝试自定义 Authorize 属性。

一个代码sn-p:

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”变量中必须有一个属性,但它逃脱了我。

想法?

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-3 authorization


    【解决方案1】:

    语法:

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

    使用named parameter。这实际上是属性类中的一个属性。由于您的类派生自AuthorizeAttribute,其中包含this property

    public string Roles { get; set; }
    

    您应该可以将它用作AuthorizeCustom 的构造函数中的参数。

    【讨论】:

    • 我是否必须专门测试此 Roles 属性,或者这是否发生在基类中,因此是否有我可以调用的结果属性,如 RolesValid ?我什么都看不到,所以我推测我需要做“if IsInRoles(Roles) {return true}”
    • 我认为它是自动合并到“base.AuthorizeCore(httpContext)”中的?
    • 是的,刚刚确认:)
    • 是的,授权方法会考虑角色。
    猜你喜欢
    • 2012-03-19
    • 1970-01-01
    • 2012-07-14
    • 1970-01-01
    • 2014-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-03
    相关资源
    最近更新 更多