在 ASP.Net Core 中使用 MiniProfiler的方法
web应用程序的性能相信是大家普遍关心的一个问题,也相信大家有很多工具可用来分析应用程序的性能并能够找到其中的瓶颈,MiniProfiler就是这个领域中的一款产品,它是一款简单的,功能强大的web应用分析工具,MiniProfiler可用来帮助我们找到慢查询,慢响应等问题。
MiniProfiler可用在Asp.Net和ASP.NetCore中,这篇文章将会讨论如何使用MiniProfiler,并通过它找到应用程序的性能问题。
安装MiniProfiler
要想使用MiniProfiler,需要通过nuget引用MiniProfiler.AspNetCore.Mvc包,可以通过VisualStudio2019的NuGetpackagemanager可视化界面安装或者通过NuGetpackagemanager命令行工具输入以下命令:
dotnetaddpackageMiniProfiler.AspNetCore.Mvc
安装好之后,接下来就要将MiniProfiler注入到ServiceCollection容器中,如下代码所示:
//Thismethodgetscalledbytheruntime.Usethismethodtoaddservicestothecontainer.
publicvoidConfigureServices(IServiceCollectionservices)
{
services.AddControllersWithViews();
services.AddMiniProfiler(options=>options.RouteBasePath="/profiler");
}
注入好之后,接下来就需要使用UseMiniProfiler扩展方法将其注入到RequestPipeline管道中,如下代码所示:
publicvoidConfigure(IApplicationBuilderapp,IWebHostEnvironmentenv,ILoggerFactoryloggerFactory)
{
app.UseMiniProfiler();
app.UseEndpoints(endpoints=>
{
endpoints.MapControllerRoute(
name:"default",
pattern:"{controller=Home}/{action=Index}/{id?}");
});
}
然后在_Layout.cshtml页面中增加如下两行命令。
@usingStackExchange.Profiling @addTagHelper*,MiniProfiler.AspNetCore.Mvc
最后需要在WebPage中指定MiniProfiler分析窗口应该显示的位置,那如何做呢?在body标签内使用mini-profiler标记,如下代码所示:
在ASP.NetCoreMVC中使用MiniProfiler
MiniProfiler会提供页面加载时间和数据库查询性能指标,接下来把程序跑起来,你会看到如下的性能指标图。
有些朋友可能就要问了,大体时间我是知道了,那如果我只想获取某一指定代码块的执行时间呢?当然也是可以的,下面的代码展示了如何去实现。
publicclassHomeController:Controller
{
ILoggerlogger;
publicHomeController(ILoggerlogger)
{
this.logger=logger;
}
publicIActionResultIndex()
{
varminiProfiler=MiniProfiler.Current;
Listauthors=newList();
miniProfiler.RenderIncludes(this.HttpContext);
using(miniProfiler.Step("GetAuthors"))
{
authors.Add(newAuthor(){Id=1,FirstName="Joydip",LastName="Kanjilal",Address="Hyderabad,India"});
authors.Add(newAuthor(){Id=2,FirstName="Stephen",LastName="Smith",Address="NY,USA"});
authors.Add(newAuthor(){Id=3,FirstName="Anand",LastName="Narayanan",Address="Chennai,India"});
authors.Add(newAuthor(){Id=4,FirstName="Steve",LastName="Jones",Address="London,UK"});
}
returnView(authors);
}
}
publicclassAuthor
{
publicintId{get;set;}
publicstringFirstName{get;set;}
publicstringLastName{get;set;}
publicstringAddress{get;set;}
}
从上面的代码中可以看到,我用using(miniProfiler.Step("GetAuthors"))做了语句块标记,理论上mini-profile窗口上应该有类似GetAuthors指标栏,接下来把程序跑起来,一起来看看效果。
除了顺向操作,你也可以指定让某些代码块不要显示在mini-profile中,需要做的是调用Ignore()即可,如下代码所示:
using(MiniProfiler.Current.Ignore())
{
//Writecodeherethatyoudon't
//wantMiniProfilertoprofile
}
使用MiniProfile分析ADO.NET查询
除了做一些常规的页面分析,还可以直接对ADO.NET查询性能进行分析,这就