使用MiniProfiler调试ASP.NET web api项目性能

MVC MiniProfiler 是 Stack Overflow 团队设计的一款对 ASP.NET MVC 的性能分析的小程序。可以对一个页面本身,及该页面通过直接引用、Ajax、Iframe 形式访问的其它页面进行监控,监控内容包括数据库内容,并可以显示数据库访问的 SQL(支持 EF、EF CodeFirst 等 )。并且以很友好的方式展现在页面上。该 Profiler 的一个特别有用的功能是它与数据库框架的集成。除了.NET 原生的 DbConnection 类,profiler 还内置了对实体框架(Entity Framework)以及 LINQ to SQL 的支持。任何执行的 Step 都会包括当时查询的次数和所花费的时间。为了检测常见的错误,如 N+1 反模式,profiler 将检测仅有参数值存在差 异的多个查询。MiniProfiler 是以 Apache License V2.0 协议发布的,你可以在 NuGet 找到。配置及使用可以看这里:http://code.google.com/p/mvc-mini-profiler

在 WebApi 中,对其性能进行分析监测是很有必要的。而悲剧的是,MVC 项目中可以使用的 MiniProfiler 或 Glimpse 等,这些都不支持 WebApi 项目,而且 WebApi 项目通常也没有界面,不能进行性能分析的交互。在这篇文章中,我们就来一步步实现为 WebApi 项目集成 Miniprofiler。集成后,我们可以监控 EF 执行效率,执行语句,页面执行时间等,这些结果将以很友好的方式显示在界面上。
本质上,集成 Miniprofiler 可以分解为三个问题:怎样监测一个 WebApi 项目的性能。将性能分析监测信息从后端发送到 UI。在 UI 显示分析监测结果。首先安装 Miniprofiler,MiniProfiler.EF6 在 Global.asax  加入

protected override void Application_Start(object sender, EventArgs e)
{
	StackExchange.Profiling.EntityFramework6.MiniProfilerEF6.Initialize();
	MiniProfiler.Settings.Results_Authorize = p => true;
	MiniProfiler.Settings.Results_List_Authorize = p => true;
	MiniProfiler.Settings.RouteBasePath = "~/profiler/";//访问路径/profiler/results 或者/profiler/results-index

	base.Application_Start(sender, e);
}


protected void Application_BeginRequest()
{

	MiniProfiler.Start();

}

protected void Application_EndRequest()
{
	MiniProfiler.Stop();
}

运行项目,http://localhost//profiler/results-index  即可看到监测结果

© 版权声明

☆ END ☆
喜欢就点个赞吧
点赞0 分享
评论 抢沙发
  • 武穆逸仙

    昵称

  • 取消回复

    请填写用户信息:

图片正在生成中,请稍后...