Execute code before/after every controller action

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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...
}

Method 2

I would recommend you to push in a Logger (probably ILogger) object as a dependency to your controller. You can control the lifetime of this logger object by a DI container (Unity, for example) – and if neccessary you can define its lifetime as request scoped. The other benefit of this soution that your code will remain testable.

Method 3

you can use modules because they both sit in a pipeline and can provide pre and post processing for the core execution of a request. BeginRequest / ActionExecuting and EndRequest / ResultExecuted. They both also provide authorization hooks.

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x