[翻译] 使用ASP.NET MVC操作过滤器记录日志

时间:2022-09-12 18:23:05

[翻译] 使用ASP.NET MVC操作过滤器记录日志

摘要:日志记录是一种常见的交错关注点(Cross-Cutting Concern),很多ASP.NET开发者会在Global.asax文件中处理它。由于MVC是构建在ASP.NET之上的,所以你可以使用同样的解 决方式,但还有更好的方法。这篇文章向你展示了使用ASP.NET MVC的操作过滤器来向Web应用程序中添加日志是多么简单。

Logging is a common Cross-Cutting Concern that many ASP.NET developers solve in the Global.asax file. Because MVC is built on top of ASP.NET you could tap into the same solution, but there is a better way. This article will show how easy it is to add logging to your web app using ASP.NET MVC Action Filters.

日志记录是一种常见的交错关注点,很多ASP.NET开发者会在Global.asax文件中处理它。由于MVC是构建在ASP.NET之上的,所以你可以使用同样的解决方式,但还有更好的方法。这篇文章向你展示了使用ASP.NET MVC的操作过滤器来向Web应用程序中添加日志是多么简单。

Action Filters give you the ability to run custom code before or after an action (or page) is hit. Applying action filters to your MVC app is simple because they are implemented as attributes that can be placed on a method (an individual Action), or a class (the entire Controller).

操作过滤器使得你可以在操作(或页面)执行之前和之后运行自定义代码。在MVC应用程序中使用操作过滤器很简单,因为它们是通过特性实现的,可以放置在方法(一个单独的操作)或类(整个控制器)前面。

To show how easy this is, we're going to take the out-of-the-box ASP.NET MVC template, and very slightly tweak it to begin logging. We'll add one class (our custom Action Filter), and salt the existing pages with our new "LogRequest" attribute.

为了看到这有多简单,我们使用了开箱即用的ASP.NET MVC模板,对其进行少许调整就可以开始记录日志了。我们将会添加一个类(自定义的操作过滤器),并用这个新的"LogRequest"特性来“调制”现有的页面。

Creating a Custom Action Filter
创建自定义操作过滤器

To create your own action filter, you simply have to
inherit from the base "ActionFilterAttribute" class that's already a
part of the MVC framework. To make this easier on myself, I've also
implemented the IActionFilter interface so that Visual Studio can
auto-generate my two methods for me.

要创建自己的操作过滤器,只需要简单地继承ActionFilterAttribute基类,该类是MVC框架的一部分。我为了更方便一些,还实现了IActionFilter接口,这样Visual Studio就会自动为我生成两个方法。

At this point, my custom action filter looks like this:

这时,我的自定义操作过滤器看起来是这样的:

 public class LogsRequestsAttribute : ActionFilterAttribute, IActionFilter
{
void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
{
// I need to do something here...
}
void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
{
// I need to do something here...
}
}
 

The ActionFilterAttribute and IActionFilter interface comes from the System.Web.Mvc namespace.

ActionFilterAttribute和IActionFilter接口来自System.Web.Mvc命名空间。

It's important to remember that this article was
written (and the sample app was compiled) for ASP.NET MVC Preview 4.
When the beta and release is eventually out, specifics of the article
may not be 100% relevant. However, this capability should remain the
same.

要记得本文(和文中的示例程序)是针对ASP.NET MVC Preview 4编写的。当beta和release版发布后,文章的细节可能不是100%有效的。不过,这一功能还是相同的。

Applying Our Custom Action Filter
应用自定义操作过滤器

Now that we have created our action filter, we need to
apply it to our Controllers or optionally, to our Actions. Because
logging is something that you would likely want on all of your "pages",
we'll simply add it at the controller level. Here is what we've added to
the two existing controllers that were supplied in the ASP.NET MVC
template.

现在我们已经创建好操作过滤器了,我们需要将其应用到控制器上,或者有选择地应用在操作上。因为你可能希望对所有的“页面”进行日志记录,我们简单地将其添加到控制器级别上。在这里我们将其添加到ASP.NET MVC模板提供的两个控制器上。

 // HandleError was already there...
[HandleError]
[LogRequest]
public class HomeController : Controller
{
...
}
// HandleError was already there...
[HandleError]
[LogRequest]
public class AccountController : Controller
{
...
}

That's it! The ASP.NET MVC framework will
automatically call our methods (OnActionExecuting and then
OnActionExecuted) when a request comes in to any of those two
controllers.

就是这样!当一个请求进入这两个控制器时,ASP.NET MVC框架会自动调用我们的方法(先是OnActionExecuting,然后是OnActionExecuted)。

At this point, all we have to do is actually implement
our logging code. Because I want to be able to easily report against my
site's activity, I'm going to log to a SQL database. Now, it's
important to note that action filters are executed synchronously (for
obvious reasons), but I don't want the user to have to wait for my
logging to happen before he can enjoy my great site. So, I'm going to
use the fire and forget design pattern.

此时,我们必须要真正实现日志记录代码了。由于我希望能简单地报告站点的活动,所以我将日志记录在SQL数据库中。要注意,操作过滤器是同步执行的(原因很明显),但我可不想让用户在访问我的牛逼的站点之前还要等着记录日志。因此,我将使用fire and forget设计模式。

When we're all done, this is what our logger will look like:

搞定所有这些之后,我们的日志记录看起来就是这样了:

 // By the way, I'm using the Entity Framework for fun.
public class LogRequestAttribute : ActionFilterAttribute, IActionFilter
{
private static LoggerDataStoreEntities DataStore = new LoggerDataStoreEntities();
void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
{
ThreadPool.QueueUserWorkItem(delegate
{
DataStore.AddToSiteLog(new SiteLog
{
Action = filterContext.ActionMethod.Name,
Controller = filterContext.Controller.ToString(),
TimeStamp = filterContext.HttpContext.Timestamp,
IPAddress = filterContext.HttpContext.Request.UserHostAddress,
});
DataStore.SaveChanges();
});
}
}

Conclusion
小结

There are a lot of features in MVC that could each
merrit their own articles, but Action Filters are definately one feature
that shows off the advantages of the MVC design pattern. Action Filters
make perfect sense for cross-cutting concerns like logging, but you can
get creative with how and why you use them.

MVC中有太多的特性,每种都能单独写成文章,但操作过滤器最能炫耀MVC设计模式的特性。操作过滤器对交错关注点有着异同寻常的意义,但如何以及为什么使用它们,就需要你发挥创造力了。

This article isn't here to show you the best way to do
logging, but rather how and why you would use ASP.NET MVC Action
Filters. Here's the source code, play around with it: MVC_CustomActionFilter_Logging.zip

这篇文章并没有介绍记录日志最好的方法,而是给出了如何以及为什么使用ASP.NET MVC操作过滤器。这里是源代码,玩得愉快:MVC_CustomActionFilter_Logging.zip

[翻译] 使用ASP.NET MVC操作过滤器记录日志的更多相关文章

  1. 使用ASP.NET MVC操作过滤器记录日志(转)

    使用ASP.NET MVC操作过滤器记录日志 原文地址:http://www.singingeels.com/Articles/Logging_with_ASPNET_MVC_Action_Filte ...

  2. ASP.NET MVC : Action过滤器(Filtering)

    http://www.cnblogs.com/QLeelulu/archive/2008/03/21/1117092.html ASP.NET MVC : Action过滤器(Filtering) 相 ...

  3. [渣翻译] 在ASP.NET MVC WebAPI项目中使用 AngularJS

    原文地址http://blog.technovert.com/2013/12/setting-up-angularjs-for-asp-net-mvc-n-webapi-project/ 我们最近发布 ...

  4. Asp.net MVC 权限过滤器实现方法的最佳实践

    在项目开发中,为了安全.方便地判断用户是否有访问当前资源(Action)的权限,我们一般通过全局过滤器来实现. Asp.net MVC 页面中常见的权限判断使用过滤器主要在以下几种情况(根据权限判断的 ...

  5. ASP.NET MVC 系统过滤器、自定义过滤器

    一.系统过滤器使用说明 1.OutputCache过滤器 OutputCache过滤器用于缓存你查询结果,这样可以提高用户体验,也可以减少查询次数.它有以下属性: Duration:缓存的时间,以秒为 ...

  6. ASP.NET MVC动作过滤器

    ASP.NET MVC提供了4种不同的动作过滤器(Aciton Filter). 1.Authorization Filter 在执行任何Filter或Action之前被执行,用于身份验证 2.Act ...

  7. 【翻译】ASP.NET MVC 5属性路由(转)

    转载链接:http://www.cnblogs.com/thestartdream/p/4246533.html 原文链接:http://blogs.msdn.com/b/webdev/archive ...

  8. Asp.net MVC 之过滤器

    整理一下MVC中的几种过滤器,以及每种过滤器是干什么用的 四种过滤器 1.AuthorizationFilter(授权过滤器) 2.ActionFilter(方法过滤器) 3.ResultFilter ...

  9. ASP.NET MVC 使用 Log4net 记录日志

    Log4net 介绍 Log4net 是 Apache 下一个开放源码的项目,它是Log4j 的一个克隆版.我们可以控制日志信息的输出目的地.Log4net中定义了多种日志信息输出模式.它可以根据需要 ...

随机推荐

  1. Android开发学习—— Broadcast广播接收者

    现实中:电台要发布消息,通过广播把消息广播出去,使用收音机,就可以收听广播,得知这条消息.Android中:系统在运行过程中,会产生许多事件,那么某些事件产生时,比如:电量改变.收发短信.拨打电话.屏 ...

  2. 《Entity Framework 6 Recipes》中文翻译系列 (13) -----第三章 查询之使用Entity SQL

    翻译的初衷以及为什么选择<Entity Framework 6 Recipes>来学习,请看本系列开篇 3-4使用实体SQL查询模型 问题 你想通过执行Entity SQL语句来查询你的实 ...

  3. Dirty Markup - 在线代码美化工具

    如果你需要一个帮助你规整书写混乱的代码的工具的话,我强烈推荐给你这个在线代码美化工具 - Dirty Markup.这个在线工具能够帮助你有效的处理HTML/HTML5,CSS和javascript代 ...

  4. Source Insight 基本使用&lpar;1&rpar;-使用Source Insight查看Android Framework 源码

    一.下载framework源码: google已经把framework源码托管在了gitHub上: https://github.com/android/platform_frameworks_bas ...

  5. oracle 存储过程的基本语法

    原文:oracle 存储过程的基本语法 1.基本结构 CREATE OR REPLACE PROCEDURE 存储过程名字(    参数1 IN NUMBER,    参数2 IN NUMBER) I ...

  6. &lbrack;&period;NET&rsqb; 使用ValidationContext快速进行模型资料的验证

    在进行WebAPI功能开发的时候,一般传统的验证资料是否合法的方式,都是透过if/else的方式进行判断若是使用ValidationContext,就可以省去很多自行撰写程式码的工作 要使用Valid ...

  7. CS229 6&period;3 Neurons Networks Gradient Checking

    BP算法很难调试,一般情况下会隐隐存在一些小问题,比如(off-by-one error),即只有部分层的权重得到训练,或者忘记计算bais unit,这虽然会得到一个正确的结果,但效果差于准确BP得 ...

  8. IIS错误提示:另一个程序正在使用此文件 进程无法访问

    在IIS管理中,启动一个配置好的网站时,提示:另一个程序正在使用此文件 进程无法访问 原因:网站绑定端口被占用 解决办法:更换绑定端口或者将占用此端口的程序关掉即可

  9. windows编程经典书籍

    本人是刚刚开始学习windows编程的,感觉看雪学院的大牛很NB.想找一些书籍来看学习学习,可是不知道看哪些书好.驱动,对菜鸟们来说真是一个很深奥的话题,所以 ,我找来了这篇文章供大家分享,以后大家发 ...

  10. CentOS Linux 7 安装教程

    建立新的虚拟机 将CentOS 7 ISO文件插入到CD-Rom 启动虚拟机,F12选择启动方式为CD/DVD 选择Install CentOS Linux 7 加载安装必要文件 选择安装过程所显示的 ...