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?
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... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With