可能有些时候需要记录Action的执行时间来优化系统功能,这时可以用过滤器来实现

第1个例子

using System;
using System.Diagnostics;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http.Controllers;
using System.Web.Mvc; namespace Mall.Site
{ /// <summary>
/// 执行耗时监测
/// </summary>
public class StopwatchFilter : ActionFilterAttribute
{
Stopwatch wat = new Stopwatch();
Stopwatch swAsync = new Stopwatch(); public override void OnActionExecuted(ActionExecutedContext filterContext)
{
swAsync.Stop();
if (swAsync.ElapsedMilliseconds>)
{
string msg = string.Format("页面{0},线程id={1},Action执行时间{2}毫秒", filterContext.HttpContext.Request.RawUrl, Thread.CurrentThread.ManagedThreadId, swAsync.ElapsedMilliseconds);
FrameWork.log4net.LogHelper.LogInfo(msg);
}
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
swAsync.Reset();
swAsync.Start();
} public override void OnResultExecuted(ResultExecutedContext filterContext)
{
wat.Stop();
if (wat.ElapsedMilliseconds>)
{
string msg = string.Format("页面{0},线程id={1},View执行时间{2}毫秒", filterContext.HttpContext.Request.RawUrl, Thread.CurrentThread.ManagedThreadId, wat.ElapsedMilliseconds);
FrameWork.log4net.LogHelper.LogInfo(msg);
}
}
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
wat.Reset();
wat.Start();
}
}
}

https://blog.csdn.net/u011511086/article/details/78710980?utm_source=copy

第2个例子方法.

nuget:下载Nlog.Config,选择Nlog.Config的目的是顺便把配置文件也下载了

修改配置文件

在ActionTime项目下应该可以看到NLog.config文件,配置文件内容如下:

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<!-- shortdate:-- level:Error、Info...-->
<variable name="logDirectory" value="${basedir}/Logs/${shortdate}/${level}"/>
<targets>
<target xsi:type="File" name="AllFile" fileName="${logDirectory}/All.log"
layout="${longdate} ■${level}${newline} ▲${stacktrace}${newline} ◇${callsite:className=True:fileName=True:includeSourcePath=True:methodName=True}${newline} ◆${message}${newline}${newline}***************************************************************************"
archiveFileName="${logDirectory}/archives/All_${shortdate}.{#####}.log"
archiveAboveSize=""
archiveNumbering="Sequence"
concurrentWrites="true"
keepFileOpen="false"/>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="AllFile" />
</rules>
</nlog>

此配置会在项目下新建Logs目录,所有日志文件都存放在里面

例:Logs\2017-03-30\Info\All.Log

新建过滤器类

接着在ActimTime项目中新建一个目录Filters,此目录用来存放自定义过滤器类

在Filters目录下新建一个类TimingActionFilter

public class TimingActionFilter : ActionFilterAttribute
{ private static readonly Logger Log = LogManager.GetCurrentClassLogger(typeof(TimingActionFilter)); //创建字典来记录开始时间,key是访问的线程Id.
private readonly Dictionary<int, DateTime> _start = new Dictionary<int, DateTime>(); //创建字典来记录当前访问的页面Url.
private readonly Dictionary<int, string> _url = new Dictionary<int, string>(); public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//过滤掉ChildAction, 因为ChildAction实际上不是一个单独的页面
if (filterContext.IsChildAction) return; var currentThreadId = System.Threading.Thread.CurrentThread.ManagedThreadId; try
{
_start.Add(currentThreadId, DateTime.Now);
_url.Add(currentThreadId, filterContext.HttpContext.Request.Url == null
? string.Empty
: filterContext.HttpContext.Request.Url.AbsoluteUri);
}
catch (Exception ex)
{
Log.Error(ex.ToString());
}
} public override void OnResultExecuted(ResultExecutedContext filterContext)
{
var currentThreadId = System.Threading.Thread.CurrentThread.ManagedThreadId;
if (!_start.ContainsKey(currentThreadId)) return; try
{ //计算出当前页面访问耗时
var timeSpan = (DateTime.Now - _start[currentThreadId]).TotalMilliseconds;
if (timeSpan > )//如果耗时超过500毫秒,就是用log4net打印出,具体是哪个页面访问超过了500豪秒,具体使用了多长时间。
{
Log.Info(string.Format("运行时间超过500毫秒,共花费{1}毫秒. URL: {0}", _url[currentThreadId], timeSpan));
}
}
catch (Exception ex)
{
Log.Error(ex.ToString());
}
finally
{
_start.Remove(currentThreadId);
_url.Remove(currentThreadId);
}
}
}

修改控制器

打开HomeController,修改Index为如下:

        public ActionResult Index()
{
Thread.Sleep();//添加延时
return View();
}

修改FilterConfig

再打开FilterConfig文件,修改代码如下:

        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new TimingActionFilter());//自己定义的过滤器
}

https://www.cnblogs.com/shensigzs/p/6645631.html

net 记录controller Action耗时的更多相关文章

  1. 在MVC或WEBAPI中记录每个Action的执行时间和记录下层方法调用时间

    刚才在博客园看了篇文章,http://www.cnblogs.com/cmt/p/csharp_regex_timeout.html  突然联想到以前遇到的问题,w3wp进程吃光CPU都挂起IIS进程 ...

  2. 记录每个action执行时间

    import org.apache.commons.lang.time.StopWatch; import org.aspectj.lang.JoinPoint; import org.aspectj ...

  3. 尝试asp.net mvc 基于controller action 方式权限控制方案可行性

    微软在推出mvc框架不久,短短几年里,版本更新之快,真是大快人心,微软在这种优秀的框架上做了大量的精力投入,是值得赞同的,毕竟程序员驾驭在这种框架上,能够强力的精化代码,代码层次也更加优雅,扩展较为方 ...

  4. PSP记录个人项目耗时情况

    四则运算编程 PSP记录个人项目耗时情况 PSP Personal Software Process Stages Time(%) Planning 计划 7 Estimate 估计这个任务需要多少时 ...

  5. asp.net MVC中获取当前URL/Controller/Action

    一.获取URL(ASP.NET通用): [1]获取完整url(协议名+域名+虚拟目录名+文件名+参数) string url=Request.Url.ToString(); [2]获取虚拟目录名+页面 ...

  6. 使用ActionFilterAttribute 记录 WebApi Action 请求和返回结果记录

    使用ActionFilterAttribute 记录 WebApi Action 请求和返回结果记录 C#进阶系列——WebApi 异常处理解决方案 [ASP.NET Web API教程]4.3 AS ...

  7. Part 2 How are the URL's mapped to Controller Action Methods?

    Part 2 How are the URL's mapped to Controller Action Methods? The answer is ASP.NET Routing.Notice t ...

  8. 返璞归真 asp.net mvc (3) - Controller/Action

    原文:返璞归真 asp.net mvc (3) - Controller/Action [索引页] [源码下载] 返璞归真 asp.net mvc (3) - Controller/Action 作者 ...

  9. ASP.NET MVC和ASP.NET Core MVC中获取当前URL/Controller/Action (转载)

    ASP.NET MVC 一.获取URL(ASP.NET通用): [1]获取完整url(协议名+域名+虚拟目录名+文件名+参数) string url=Request.Url.ToString(); [ ...

随机推荐

  1. WordCloud 简介

    WordCloud 简介 GitHub GitHub:https://github.com/amueller/word_cloud example:https://github.com/amuelle ...

  2. codeforces|CF13C Sequence

    大概的题意就是每次可以对一个数加一或者减一,然后用最小的代价使得原序列变成不下降的序列. 因为是最小的代价,所以到最后的序列中的每个数字肯定在原先的序列中出现过.(大家可以想一下到底是为什么,或者简单 ...

  3. Delphi XE8帮助中的REST相关内容。

    Delphi XE8的离线帮助是我见过的最好的Delphi帮助文档了,内容相当详细和丰富,几乎涵盖了Delphi的方方面面!! Delphi XE8的帮助文档在哪里?“XE8安装目录\Help\Doc ...

  4. OCP 12c最新考试原题及答案(071-4)

    4.(4-11) choose two:View the Exhibit and examine the data in the PRODUCT_INFORMATION table.Which two ...

  5. jquery.nav.js定位导航滚动插件

    jQuery.nav.js插件代码: /* * jQuery One Page Nav Plugin * http://github.com/davist11/jQuery-One-Page-Nav ...

  6. 虚拟机CentOS防火墙设置

    CentOS6关闭防火墙使用以下命令, 开启防火墙 systemctl start firewalld //临时关闭 # service iptables stop //禁止开机启动 # chkcon ...

  7. [译文]casperjs的API-colorizer模块

    colorizer模块包含了一个Colorizer类,它能够生成一个标准化的颜色字符串: var colorizer = require('colorizer').create('Colorizer' ...

  8. js实现checkbox全选,全部选和反选效果

    效果: 源码: <!DOCTYPE html> <html lang="en"> <head> <meta charset="U ...

  9. Echo团队Alpha冲刺随笔 - 第七天

    项目冲刺情况 进展 服务器部署完成.小程序改了几个BUG,WEB端大部分完成,后端主体功能大致完成. 问题 交接的时候出现很多新问题 心得 软工实践真棒!yeah!!! 今日会议内容 黄少勇 今日进展 ...

  10. vim编辑器基本操作及文件权限,sudo命令等介绍

    一:vim 操作命令,在命令模式下操作 pageup 往上翻页 pagedown 往下翻页 H 移动到屏幕首行 gg 移动光标到文档的首行 前面加数字n表示移动到n行内容 G 移动到文档最后一行/查找 ...