【问题标题】:Creating Custom Authorization Attribute with MVC使用 MVC 创建自定义授权属性
【发布时间】:2013-08-13 12:50:43
【问题描述】:

我对 MVC 很陌生,这是我第一次尝试使用它创建一个站点,并且是简单的成员。我正在处理的要求是需要同时使用角色和权限。

所以我需要一个额外的授权方法,就像角色一样工作。 所以例如,我需要这个工作: [AuthorizeUser(Permission = "Browse")]

我找到了多个创建自定义授权属性的示例,但到目前为止,没有一个对我真正有用。传递的值丢失了,我不断收到空值异常。

我发现了多个类似的问题,但我找到的代码对我不起作用。 以下是我根据各种 stackoverflow 问题中的代码尝试过的示例。


public class AuthorizeUser : AuthorizeAttribute
    {
        public string AccessLevel { get; set; }
     protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            var isAuthorized = base.AuthorizeCore(httpContext);
            if (!isAuthorized)
            {
                return false;
            }

            // My method to get permisions
            userPermissions=getpermsions();


            if (userPermissions.Contains(this.Permission))//**** problem line
            {
                return true;
            }
            else
            {
                return false;
            }
        }

}

问题是这一行: if (userPermissions.Contains(this.Permission))

this.Permission 始终为空。 我已经尝试了多种变体,但它始终为空。

我可以使用其他一些替代方法,但是这行不通让我发疯。 好像应该这样。

【问题讨论】:

    标签: asp.net-mvc authorization custom-attributes


    【解决方案1】:

    您在调用控制器中的属性时使用的属性名称似乎与 AuthorizeUser 类中指定的名称不同。将属性 AccessLevel 更改为 Permission

    像这样:

    public class AuthorizeUser : AuthorizeAttribute
    {
        public string Permission { get; set; }
    
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
    

    您的控制器中的调用将设置属性值:

    [AuthorizeUser(Permission = "Browse")]
    public ViewResult Index()
    

    【讨论】:

    • 已编辑答案以从“ReAuthorizeAttribute”中更正类名。这是我在自己的系统中使用的东西。
    猜你喜欢
    • 2015-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-01
    • 1970-01-01
    相关资源
    最近更新 更多