Execute code before / after each controller action

I have an ASP.NET MVC application for which I want to log events. I already have a log class with all the necessary tools, but I need to create an instance and close it explicitly (because it opens files, so I cannot depend on GC). My actions will look like this:

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

Or I could use the using block, but it would be a little less intrusive, and that would create problems with exception handling. I read about ActionFilters , which I could use to create and close my log, but then I would not have access to the log object inside the method.

Do you have any suggestions? How could I avoid repeating the code?

+5
source share
3 answers

If other suggestions do not work, or you need to do something other than logging, keep in mind that you can override the OnActionExecuting method (often in the 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... } 
+13
source

I would recommend that you insert a Logger object (possibly ILogger) as a function of your controller. You can control the lifetime of this registration object using a DI container (for example, Unity) - and, if necessary, you can define its lifetime as a request area. Another advantage of this rule is that your code will remain in control.

+2
source

you can use modules because they are both in the pipeline and can provide preprocessing and post-processing for the main execution of the request. BeginRequest / ActionExecuting and EndRequest / ResultExecuted. Both of them also provide authorization hooks.

http://msdn.microsoft.com/en-us/library/aa719858(v=vs.71).aspx

0
source

Source: https://habr.com/ru/post/1204411/


All Articles