Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute code before/after every controller action

Tags:

I have an ASP.NET MVC application for which I want to log events. I have already a Log class with all the tools I need, but I have to instantiate and to close it explicitly (because it opens files, so I can't depend on the GC). My actions would look like this:

public ActionResult MainMenu() {     CreateLog();      // Do controller stuff     Log(message);     // Do more controller stuff      CloseLog();     return View(mModel); } 

Or I could use a using block, but it would be just a little less intrusive AND it would create troubles with exception handling. I've read about ActionFilters, which I could use to create and close my Log, but then I would have no way to access the Log object inside the method.

Do you have any suggestion? How could I avoid having to repeat the code?

like image 822
Simone Avatar asked Oct 10 '14 11:10

Simone


1 Answers

If the other suggestions don't work or if you need to do things other than just logging also be aware that you can override the OnActionExecuting method (often in a base class for reuse).

// Custom controller. public class CustomController : Controller {     protected override void OnActionExecuting(ActionExecutingContext filterContext)     {         // Do whatever here...     } }  // Home controller. public class HomeController : CustomController {     // Action methods here... } 
like image 190
David Godwin Avatar answered Sep 28 '22 18:09

David Godwin