1

I need to run code after all Actions in asp.net core.

Apparently, the answer is not to register a new middleware, as middlewares don't have access to the Action return value, they have access to the executed ActionResult.

Apparently, the answer is not to define a new ActionFilter, as I need to use it on every action.

So here is the question: How can I run code before and after every action in asp.net core, in a way that I have access to method input and output?

Set
  • 47,577
  • 22
  • 132
  • 150
Alireza
  • 5,421
  • 5
  • 34
  • 67
  • 1
    What about an `IActionFilter`? You can add it to filters via options on `.UseMvc(options)`. – ProgrammingLlama Jan 21 '18 at 12:08
  • Would it be an option to call this code from the constructor and override Dispose to run code before the controller is disposed. –  Jan 21 '18 at 12:53
  • @RuardvanElburg Interesting suggestion. BTW, I'm looking for a "register once, wroks everywhere" solution. – Alireza Jan 21 '18 at 13:18
  • @john Can you elaborate? – Alireza Jan 21 '18 at 13:18
  • 1
    @Alireza - ActionFilter could be globally registered and so it will be applied to each action. Look into this [SO post](https://stackoverflow.com/questions/41972518/how-to-add-global-filters-in-asp-net-core) for example – Set Jan 21 '18 at 14:14
  • Instead of inheriting from Controller you could inherit from MyController (which inherits from Controller), where you add the lines of code. –  Jan 21 '18 at 14:34
  • 1
    @RuardvanElburg: One shouldn't abuse the dispose pattern for this, when there are clean ways and hooks to do that (action filters, middleware). Dispose is only called when the controller is being disposed/cleaned up and this happens on the **end** of the request. By that time the result has already been written to the stream (connection to the browser) – Tseng Jan 21 '18 at 14:55
  • ActionFilters and the ability to register them globally is the way to go. Thanks everyone. – Alireza Jan 21 '18 at 15:12

0 Answers0