可能有些时候需要记录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. Javascript获取select的选中值和选中文本(转载)

    var obj = document.getElementById(”select_id”); //selectid var index = obj.selectedIndex; // 选中索引 va ...

  2. 如何获得Android设备名称(ADB命令详细介绍)

    豌豆荚.360手机管家等软件可以获取android设备名称,显示在界面上,如下图: 我们自己如何来获取设备名称 呢?答案如下: 在命令行中输入“adb shell”进入shell之后,再输入“cat ...

  3. [转]解读Unity中的CG编写Shader系列8——多光源漫反射

    前文中完成最简单的漫反射shader只是单个光源下的漫反射,而往往场景中不仅仅只有一个光源,那么多个光源的情况下我们的物体表面的漫反射强度如何叠加在一起呢?前文打的tag "LightMod ...

  4. css3中的translate,transform,transition的区别

    translate:移动,transform的一个方法               通过 translate() 方法,元素从其当前位置移动,根据给定的 left(x 坐标) 和 top(y 坐标) ...

  5. 图论 竞赛图(tournament)学习笔记

    竞赛图(tournament)学习笔记 现在只是知道几个简单的性质... 竞赛图也叫有向完全图. 其实就是无向完全图的边有了方向. ​ 有一个很有趣的性质就是:一个tournament要么没有环,如果 ...

  6. 斐讯K2P配置文件破解笔记

    手上有一个斐讯K2P路由器,刷机前我想把原机带的固件备份出来.搜到恩山A大开启telnet.固件备份的教程,里面提到了配置文件破解的方法,心血来潮试了一下,发现算出的密码不能解密,一直报"b ...

  7. POJ1591 M*A*S*H (JAVA)

    这水题,真的坑 测试数据最后有空行,如果用sc.hasNextLine()判断,会RE 要改为sc.hasNext() 搞了我一上午,烦死 import java.util.*; public cla ...

  8. 2016级算法第四次上机-F.AlvinZH的最“长”公共子序列

    940 AlvinZH的最"长"公共子序列 思路 DP,难题. \(dp[i][j]\) :记录A的前i个字符与B的前j个字符变成相同需要的最小操作数. 初始化:dp[i][0] ...

  9. Machine learning吴恩达第二周coding作业(选做)

    1.Feature Normalization: 归一化的处理 function [X_norm, mu, sigma] = featureNormalize(X) %FEATURENORMALIZE ...

  10. UICollectionView 自定义横向排版

    .h #import <UIKit/UIKit.h> @interface JHCollectionViewFlowLayout : UICollectionViewFlowLayout ...