在每个控制器动作之前/之后执行代码 [英] Execute code before/after every controller action

查看:189
本文介绍了在每个控制器动作之前/之后执行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要记录事件的ASP.NET MVC应用程序.我已经有了一个Log类,其中包含我需要的所有工具,但是我必须实例化并显式关闭它(因为它会打开文件,所以我不能依赖于GC).我的动作如下所示:

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);
}

或者我可以使用一个using块,但是它的介入性要小一些,并且会给异常处理带来麻烦.我已经读过有关ActionFilters的信息,可以用来创建和关闭Log,但是随后我将无法访问该方法内部的Log对象.

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?

推荐答案

如果其他建议不起作用,或者您需要做的不仅仅是日志记录,还请注意您可以覆盖OnActionExecuting方法(通常在重用的基类).

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

这篇关于在每个控制器动作之前/之后执行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆