MiniProfiler(https://miniprofiler.com/)是一个轻量级且简单易用的分析工具库,它可以用来分析ASP.NET Core应用。
优点
针对ASP.NET Core MVC应用,使用MiniProfiler的优点是:它会把结果直接放在页面的左下角,随时可以点击查看;这样的话就可以感知出你的程序运行的怎么样;同时这也意味着,在你开发新功能的同时,可以很快速的得到反馈。
一、安装配置MiniProfiler
在现有的ASP.NET Core MVC项目里,通过Nuget安装MiniProfiler :
Install-Package MiniProfiler.AspNetCore.Mvc
当然也可以通过Nuget Package Manager可视化工具安装

接下来配置MiniProfiler,总共分三步:
第一步,来到Startup.cs的ConfigureServices方法里,添加services.AddMiniProfiler();
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); // 当然这个方法还可以添加一个lambda表达式作为参数,从而做一些自定义的配置: services.AddMiniProfiler(options => { // 设定弹出窗口的位置是左下角 options.PopupRenderPosition = RenderPosition.BottomLeft; // 设定在弹出的明细窗口里会显式Time With Children这列 options.PopupShowTimeWithChildren = true; }); }第二步,来到来到Startup.cs的Configure方法里,添加app.UseMiniProfiler();
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment enveXKNJg) { ... // 最重要的一点是就是配置中间件在管道中的位置,一定要把它放在UseMvc()方法之前。 app.UseMiniProfiler(); } // 但是如果你只想分析一句话,那么使用using语句就显得太麻烦了,这种情况下可以使用 Inline() 方法: var users = await MiniProfiler.Current.Inline(async () => await _context.Users.ToListAsync(), "计算第一步"); return View(users);#endif }使用 using 语句块嵌套结果展示:

使用 Inline() 方法结果展示:

自定义分析 CustomTiming
有时候,分析一些例如请求外部动作的时候,上面讲的做法可能不太灵光,这里我们就可以使用CustomTime()方法
public async Task<IActionResult> Privacy() { // 这个例子里,我们使用 MiniProfiler.Current.CustomTiming() 方法。 // 第一个参数是一个用于分类的字符串,这里我用的是http请求,所以写了http; // 第二个参数是命令字符串,这里我用不上,暂时留空; // 第三个参数是执行类型,这里我用的是Get请求,所以写了GET; using (CustomTiming timing = MiniProfiler.Current.CustomTiming("http", string.Empty, "GET")) { var url = "http://27.24.159.155"; var httpClient = new HttpClient { BaseAddress = new Uri(url) }; httpClient.DefaultRequestHeaders.Clear(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var response = await httpClient.GetAsync("/system/resource/code/news/click/dynclicks.jsp?clickid=1478&owner=1220352265&clicktype=wbnews"); timing.CommandString = $"URL:{url}nr Response Code:{response.StatusCode}"; if (!response.IsSuccessStatusCode) { www.easck.com throw new Exception("Error fetching data from API"); } var clickTimes = await response.Content.ReadAsStringAsync(); ViewData["clickTimes"] = clickTimes; } return View(); }运行程序,可以看到窗口的右侧出现了http这一列:
153.1 (1),这就是使用CustomTiming分析的那段代码,它请求的URL和返回码都显示了出来。
三、案例源码:
MiniProfilerCoreDemo
到此这篇关于ASP.NET Core使用MiniProfiler分析应用的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持我们。








