Execute code before/after every controller action

前端 未结 3 1496
梦毁少年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: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...
    }
    

提交回复
热议问题