简体   繁体   中英

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 .

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. OnActionExecutionAsync() and next() runs at different level in the filters pipeline :

  • await base.OnActionExecutionAsync(context, next); will invoke the parent's OnActionExecutionAsync(context,next) , thus do the following in sequence:
    1. call the OnActionExecuting(executingContext)
    2. invoke the action body
    3. call the 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) )

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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