C# 何时需要包括/排除MVC操作过滤器的基本调用?

C# 何时需要包括/排除MVC操作过滤器的基本调用?,c#,.net,asp.net-mvc-4,C#,.net,Asp.net Mvc 4,在使用遗留应用程序时,我注意到MVC过滤器的两种不同实现方式如下: 例1: [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public class TestFilterAttribute : ActionFilterAttribute, IActionFilter { void IActionFilter.OnActio

在使用遗留应用程序时,我注意到MVC过滤器的两种不同实现方式如下:

例1:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class TestFilterAttribute : ActionFilterAttribute, IActionFilter
{
    void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
    {
        // Code here...
        base.OnActionExecuted(filterContext);
    }

    void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Code here...
        base.OnActionExecuting(filterContext);
    }
}
例2:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class TestFilterAttribute : ActionFilterAttribute, IActionFilter
{
    void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
    {
        // Code here...
    }

    void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Code here...
    }
}
是否有理由包括/排除基类调用?

C#没有一个概念可以用来表示“派生类必须/不得调用基类实现”。有一个
abastract
在层次结构的第一层上说“派生的必须提供实现,不能调用base”,这在某种程度上有所帮助,但对于可选方法(如操作过滤器)来说,它有缺点

因此,当一个人应该/必须/不得调用基本实现时,不可能做出一般性的决定

在ActionFilters的情况下,
OnXxxx
方法的基本实现是空的,所以无论您是否调用它都没有区别。如果您继承下一层类(比如
SpecialFilter
BaseFilter
ActionFilter
)-在这种情况下,不调用基类将产生显著的差异(这可能是有意的,希望它在代码中有注释)


在我工作过的地方,调用基本实现是一种习惯,除非文档中明确禁止。当基类未被调用时,通常会添加注释说明原因。

在这种情况下,调用
base
方法没有意义,因为您从默认实现为空(来自反编译源)的
抽象类派生:

//
///在调用操作方法之前发生。
/// 
///行动背景。
公共虚拟void OnActionExecuting(HttpActionContext-actionContext)
{
}
/// 
///在调用操作方法后发生。
/// 
///在上下文中执行的操作。
公共虚拟void OnActionExecuted(HttpActionExecuteContext ActionExecuteContext)
{
}
但是,如果有一天,
ActionFilterAttribute
的实现发生了变化,那么您可以从调用基本方法中获益。但这只是一个假设,这取决于你,因为它取决于这个类可能有什么新特性(如果有的话)

/// <summary>
/// Occurs before the action method is invoked.
/// </summary>
/// <param name="actionContext">The action context.</param>
public virtual void OnActionExecuting(HttpActionContext actionContext)
{
}

/// <summary>
/// Occurs after the action method is invoked.
/// </summary>
/// <param name="actionExecutedContext">The action executed context.</param>
public virtual void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
}