【问题标题】:How to add a overload to MVCs Authorize Attribute?如何向 MVC 授权属性添加重载?
【发布时间】:2013-03-26 01:09:17
【问题描述】:

我过去经常使用[Authorize] 属性,它还允许你做这样的事情:

[Authorize(Users = "test")]

但是,我想再添加一个,

[Authorize(IsPermitted= PermissionsEnum.ThePermission)]

我已经写出了决定是否允许用户获得该权限的逻辑,但我不确定如何将该重载添加到授权属性。

如果可能的话,我不希望创建一个完全独立的授权属性。

【问题讨论】:

  • 即使你可以“重载”或扩展现有的授权属性,你会为自己节省多少?你还是要覆盖authorizecore来改变逻辑...

标签: asp.net-mvc asp.net-membership authorization


【解决方案1】:

好吧,正如@Dave A 在 cmets 上所说,您可以扩展本机 Authorize 属性并实现自己的授权方法,例如:

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    // create your custom property
    public PermissionsEnum IsPermitted { get; set; }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        bool authorized = // create your own validation and return a bool value                
        if (authorized)
        {
            return false;       
        }

            // if you want to have the nativa validation, call it from the base method
        return base.AuthorizeCore(httpContext);
    }
}

并记得使用自定义授权属性来装饰您的控制器/操作,例如:

[MyAuthorize(IsPermitted = PermissionsEnum.Sales)]
public class OrderController : Controller 
{
   // actions...    
}

【讨论】:

    【解决方案2】:

    很遗憾,你不能。您可以设置的唯一可能的属性是 用户和角色。所以你必须做一个单独的属性类。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-29
      • 1970-01-01
      • 1970-01-01
      • 2018-04-03
      • 2018-02-14
      • 1970-01-01
      相关资源
      最近更新 更多