C#:从基类检查注释架构

问题描述 投票:0回答:1

有什么方法可以从基类检查模式注释?简单说明抛出一个例子:

我有这2个控制器

[Authorize]
public class HomeController : _baseController
{
   //Some actions here    
}

[AllowAnonymous]
public class OtherController : _baseController
{
   //Some actions here    
}

然后,我有了这个覆盖OnActionExecuting的基类。目的是在控制器具有注释的情况下执行某些操作。

public class _baseController
{
   public override void OnActionExecuting(ActionExecutingContext context)
    {
        base.OnActionExecuting(context);

        if(context.Controller.hasAnnotation("Authorize")){
              //do something
        }
        else if(context.Controller.hasAnnotation("AllowAnonymous")){
              //do something
        }
    }    
}

显然context.Controller.hasAnnotation不是有效的方法。但是你明白了。

c# data-annotations
1个回答
0
投票

如评论中所建议,以下内容应为您工作:

public class _baseController
{
public override void OnActionExecuting(ActionExecutingContext context)
{
    base.OnActionExecuting(context);

   System.Attribute[] attrs = System.Attribute.GetCustomAttributes(context.Controller.GetType());
}    
}
© www.soinside.com 2019 - 2024. All rights reserved.