【问题标题】:Could base class attribute be triggered first?可以先触发基类属性吗?
【发布时间】:2021-03-02 19:54:06
【问题描述】:

看起来在 .NET 中,基类属性是在属于继承类的属性之后触发的。在我看来,还是我做错了什么?。

我的应用程序中的所有类都继承自具有[AuthorizationAttribute] 的基类,但只有一些类具有[LoggingAttribute]。 当我在 HomeController 中访问方法时,为什么我的 [LoggingAttribute] 在授权之前被命中,我如何才能先触发基类授权属性,然后再触发记录?

[AuthorizationAttribute]
public class BaseController 
{
  //....class methods
}

[LoggingAttribute]
public class HomeController: BaseController 
{
  //....class methods
}

属性:

 public class AuthorizationAttribute : ActionFilterAttribute
    {
     //...API token gets parsed into Id/Pw 
    }

    public class LoggingAttribute: ActionFilterAttribute
    {
     //...Logging record saved with Id/pw established above
    }

【问题讨论】:

    标签: c# asp.net-mvc inheritance attributes polymorphism


    【解决方案1】:

    对于这种特定情况,由于它是关于授权的,因此请确保从AuthorizeAttribute 派生您的自定义AuthorizationAttribute 或实现IAuthorizationFilter

    授权过滤器在操作过滤器属性之前执行。

    这保证了控制器操作方法只有在获得授权时才会执行。

    【讨论】:

    • 你说得对,IAuthorizationFilter 继承确实使 Base 类属性首先被命中,但我完全不需要这个额外的逻辑,看起来包含的接口 ExecuteAuthorizationFilterAsync() 方法需要要返回的 HttpResponseMessage 正在其他地方构建。重建这将是一次巨大的改革。还有其他建议吗?
    • @InspiredBy 你可以试试明确设置Order;例如[AuthorizationAttribute(Order=1)][LoggingAttribute(Order=2)] - 我自己从未尝试过。
    • @InspiredBy 想知道为什么不从AuthorizeAttribute 继承;从AuthorizeCore返回只有一个bool
    猜你喜欢
    • 2020-05-10
    • 2010-10-03
    • 1970-01-01
    • 2015-08-24
    • 1970-01-01
    • 1970-01-01
    • 2018-11-24
    • 1970-01-01
    • 2011-03-05
    相关资源
    最近更新 更多