简体   繁体   English

如何在ASP.NET Core中使用OnActionExecutionAsync

[英]How to use OnActionExecutionAsync in ASP.NET Core

How is this method overridden? 如何覆盖此方法?

Assume an inheritence graph like so. 假设这样的继承图。

FeatureController : BaseController : Controller { }

I'd like to run code before execution and after execution, and do so in both FeatureController and BaseController . 我想在执行之前和执行之后运行代码,并在FeatureControllerBaseController中都这样做。

It's confusing because there's two things that can be awaited; 这令人困惑,因为有两件事情需要等待。

await base.OnActionExecutionAsync(context, next);

And

await next();

It's just not clear to me how to use this virtual properly. 我不清楚如何正确使用此虚拟机。

Controller itself is an implementation of Action Fitler. Controller本身是Action Fitler的实现。 OnActionExecutionAsync() and next() runs at different level in the filters pipeline : OnActionExecutionAsync()next()在过滤器管道中的不同级别上运行:

  • await base.OnActionExecutionAsync(context, next); will invoke the parent's OnActionExecutionAsync(context,next) , thus do the following in sequence: 将调用父级的OnActionExecutionAsync(context,next) ,从而按顺序执行以下操作:
    1. call the OnActionExecuting(executingContext) 调用OnActionExecuting(executingContext)
    2. invoke the action body 调用动作主体
    3. call the OnActionExecuted(executedContext) 调用OnActionExecuted(executedContext)
  • await next(); will only invoke the action body itself. 只会调用动作主体本身。

In short, both of them invoke the action body, however, the base.OnActionExecutionAsync(ctx,next) will also trigger hooks (ie OnActionExecuting(executingCtx) and OnActionExecuted(executedCtx) ) 简而言之,它们都调用了动作主体,但是base.OnActionExecutionAsync(ctx,next)也会触发钩子(即OnActionExecuting(executingCtx)OnActionExecuted(executedCtx)

In the end - well, so far at least - I've ended up using the Async virtual to perform I/O and asynchronous work and then save any interesting results to fields. 最后(至少到目前为止),我最终使用Async虚拟来执行I / O和异步工作,然后将任何有趣的结果保存到字段中。

Then I use the old, synchronous virtuals as before. 然后,我像以前一样使用旧的同步虚拟机。 These then refer to the fields for any state they need in their logic. 然后,它们会参考字段中逻辑所需的任何状态。 Does the trick, even if I'm not sure its the right way. 即使我不确定它的正确方法,也可以解决问题。


As background, the problem I'm solving is adding items to a list holding main navigation links. 作为背景,我要解决的问题是将项目添加到包含主要导航链接的列表中。 I want some basic site-wide links to go in first, then contextual links for the page requested, then some more site-wide links to finish off. 我希望先添加一些基本的站点范围链接,然后再请求页面的上下文链接,然后再完成一些站点范围的链接。

A veritable link sandwich. 真正的三明治三明治。 Yum. 好吃

Arguably my solution could be improved by using composition instead of inheritance, ie inject a sandwich maker (like a Breville) into all my controllers and have non of this in the base controller, avoiding the base-me-base coordination. 可以说我的解决方案可以通过使用合成而不是继承来进行改进,即将三明治制作器(如Breville)注入到我的所有控制器中,并且在基本控制器中不添加此控件,从而避免了基于基点与基点的协调。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM