简体   繁体   English

在每个控制器操作之前/之后执行代码

[英]Execute code before/after every controller action

I have an ASP.NET MVC application for which I want to log events. 我有一个ASP.NET MVC应用程序,我想记录事件。 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). 我已经有了一个包含我需要的所有工具的Log类,但我必须实例化并明确地关闭它(因为它打开文件,所以我不能依赖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. 或者我可以使用一个using块,但它只是一点点干扰,它会产生异常处理的麻烦。 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. 我已经阅读了ActionFilters ,我可以用它来创建和关闭我的Log,但是后来我无法访问方法中的Log对象。

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). 如果其他建议不起作用或者除了记录之外还需要执行其他操作,请注意您可以覆盖OnActionExecuting方法(通常在基类中重用)。

// Custom controller.
public class CustomController : Controller
{
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Do whatever here...
    }
}

// Home controller.
public class HomeController : CustomController
{
    // Action methods here...
}

I would recommend you to push in a Logger (probably ILogger) object as a dependency to your controller. 我建议你将Logger(可能是ILogger)对象作为依赖项推入控制器。 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. 您可以通过DI容器(例如Unity)控制此记录器对象的生命周期 - 如果需要,您可以将其生命周期定义为请求范围。 The other benefit of this soution that your code will remain testable. 这个问题的另一个好处是您的代码仍然可以测试。

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. BeginRequest / ActionExecuting和EndRequest / ResultExecuted。 They both also provide authorization hooks. 它们都提供授权挂钩。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM