首页 > 解决方案 > 如何在 ASP.NET Core 中使用 OnActionExecutionAsync

问题描述

这个方法是如何被覆盖的?

假设这样的继承图。

FeatureController : BaseController : Controller { }

我想在执行之前和执行之后运行代码,并且在 和 中都这样FeatureControllerBaseController

这很令人困惑,因为有两件事可以等待;

await base.OnActionExecutionAsync(context, next);

await next();

我只是不清楚如何正确使用这个虚拟。

标签: c#asp.net-core

解决方案


Controller它本身就是一个 Action Fitler 的实现。OnActionExecutionAsync()next()在过滤器管道中的不同级别运行:

  • await base.OnActionExecutionAsync(context, next);将调用父母的OnActionExecutionAsync(context,next),因此按顺序执行以下操作:
    1. 打电话给OnActionExecuting(executingContext)
    2. 调用动作主体
    3. 打电话给OnActionExecuted(executedContext)
  • await next();只会调用动作主体本身。

简而言之,它们都调用了动作主体,但是,它们base.OnActionExecutionAsync(ctx,next)也会触发钩子(即OnActionExecuting(executingCtx)OnActionExecuted(executedCtx)


推荐阅读