Execute code before/after every controller action

前端 未结 3 1482
梦毁少年i
梦毁少年i 2020-12-24 13:42

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

相关标签:
3条回答
  • 2020-12-24 14:24

    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

    0 讨论(0)
  • 2020-12-24 14:26

    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...
    }
    
    0 讨论(0)
  • 2020-12-24 14:32

    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.

    0 讨论(0)
提交回复
热议问题