c# - 如何在 ASP.NET Core 中使用 OnActionExecutionAsync
问题描述
这个方法是如何被覆盖的?
假设这样的继承图。
FeatureController : BaseController : Controller { }
我想在执行之前和执行之后运行代码,并且在 和 中都这样FeatureController
做BaseController
。
这很令人困惑,因为有两件事可以等待;
await base.OnActionExecutionAsync(context, next);
和
await next();
我只是不清楚如何正确使用这个虚拟。
解决方案
Controller
它本身就是一个 Action Fitler 的实现。OnActionExecutionAsync()
并next()
在过滤器管道中的不同级别运行:
await base.OnActionExecutionAsync(context, next);
将调用父母的OnActionExecutionAsync(context,next)
,因此按顺序执行以下操作:- 打电话给
OnActionExecuting(executingContext)
- 调用动作主体
- 打电话给
OnActionExecuted(executedContext)
- 打电话给
await next();
只会调用动作主体本身。
简而言之,它们都调用了动作主体,但是,它们base.OnActionExecutionAsync(ctx,next)
也会触发钩子(即OnActionExecuting(executingCtx)
和OnActionExecuted(executedCtx)
)
推荐阅读
- http - 从 http 站点提取音频流(在线广播)
- html - 根据容器宽度减小标签文本大小
- c++ - 为什么这个 stl 函数调用会导致不正确的布尔评估?
- c# - 在 c# 中使用来自控制台应用程序的数据注释仅验证模型类的几个属性
- java - 更新数据库中的图片
- javascript - 将带有 & 的 URL 变量从 JS 传递到 PHP 导致“&”省略
- c++ - 我是否需要通过锁来保护对 Boost MultiIndex 索引(索引本身)的访问?
- java - 消除浮点舍入错误的技巧?
- pygame - Pygame,我的圆圈在我将它存储在一个变量中后变成了一个矩形,我该如何防止这种情况发生
- javascript - 如果在表单提交时未选中收音机,则会发出警报