可能有些时候需要记录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. WDF(Windows Driver Frameworks)驱动框架源码!!

    微软官方提供源码:https://github.com/Microsoft/Windows-Driver-Frameworks

  2. 如果使用安卓4.4的SD卡?

    安卓4.4默认情况下,后安装的程序无权写入数据到SD卡中,那么是否我们就不能用了?看了很多文章,都说要Root,随后修改配置文件.我觉得这不是很好的方法,Root之后的安卓会有很大风险,这不是最好的办 ...

  3. leetcode 213. 打家劫舍 II JAVA

    题目: 你是一个专业的小偷,计划偷窃沿街的房屋,每间房内都藏有一定的现金.这个地方所有的房屋都围成一圈,这意味着第一个房屋和最后一个房屋是紧挨着的.同时,相邻的房屋装有相互连通的防盗系统,如果两间相邻 ...

  4. [AGC006E] Rotate 3x3 树状数组+贪心

    Description ​ XFZ在北京一环内有一套房. ​ XFZ房子的地砖呈网格状分布,是一个3∗N3∗N的网格.XFZ在买下这套房时,每个地砖上有一个数字,位置为(i,j)(i,j)的地砖上的数 ...

  5. samba使用

    一. samba安装 1. 安装:apt-get install samba samba-common smbclient 安装成功后,会默认启动samba服务, 可用ps-ef | grep smb ...

  6. PHP中SimpleXMLElement对象字符编码

    最近在使用SimpleXMLElement来生成和解析XML. 由于我们使用PHP开发的这边使用UTF-8编码,而对方使用GBK编码,因此就遇到了中文字符编码问题. 后来发现,XML内部的编码与其头 ...

  7. Tutorial 01 4,5题

    .任务四: 程序设计思想:利用Math.random()产生一个char类型的字符,再利用for循环是他们相加,最后将他们放在一个消息框中输出.   程序流程图:   源程序:           p ...

  8. jquery 实现动画效果(各种方法)

    1.show()和hide()和toggle()(这是show和hide的一个综合,一个按钮就实现显示和隐藏) 效果: 代码: <button type="button" c ...

  9. IIS服务器环境下某路径下所有PHP接口无法运行报500.19错误

    IIS服务器环境下某路径(文件夹)下所有PHP接口无法运行报500.19错误 环境:IIS8.5 + php7.2.1 错误描述:某目录下(如 d:\web\A)所有php接口文档运行错误,接口测试工 ...

  10. [转] Centos 系统swap虚拟内存添加与删除配置

    [From]https://blog.csdn.net/lengyue1084/article/details/51405640 [From]https://yuukis.cn/24/ SWAP是Li ...