使用 MiniProfiler 来分析 ASP.NET Core 应用

 

使用 MiniProfiler 来分析 ASP.NET Core 应用

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 env)
{
... // 最重要的一点是就是配置中间件在管道中的位置,一定要把它放在UseMvc()方法之前。
app.UseMiniProfiler(); app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}

第三步,将MiniProfiler的Tag Helper放到页面上

  • _ViewImports 页面引入 MiniProfiler 的 Tag Helper :
    ...

    @using StackExchange.Profiling

    ...
@addTagHelper *, MiniProfiler.AspNetCore.Mvc
  • 将 MiniProfiler 的Tag Helper 放入 _Layout.cshtml 中:
    ...

    <footer class="border-top footer text-muted">
<div class="container">
&copy; 2019 - MiniProfilerCoreDemo - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</div>
</footer> @* 其实放在页面的任意地方都应该可以,但是由于它会加载一些脚本文件,所以建议放在footer下面: *@@* 其实放在页面的任意地方都应该可以,但是由于它会加载一些脚本文件,所以建议放在footer下面: *@
<mini-profiler /> <environment include="Development">
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.js"></script>
</environment> ... @RenderSection("Scripts", required: false)
</body>
</html>

运行应用,可以看到左下角就是MiniProfiler:

点击它之后会弹出窗口,里面有每个步骤具体的耗用时间。

二、MiniProfiler 具体使用

分析局部代码

前面的例子里,我们使用MiniProfiler分析了页面整个流程的时间。而MiniProfiler也可以用来分析一段代码所耗用的时间。看例子:

    public async Task<IActionResult> Index()
{
#if !DEBUG
// 这里我们使用了using语句,里面使用了 MiniProfiler 类的 Current 属性,在该属性上面有一个Step()方法,
// 它可以用来分析using语句里面的代码,在Step方法里,要提供一个具有描述性的名称来表示该段代码做的是什么动作,这个名称会显示在结果里。
using (MiniProfiler.Current.Step("计算第一步"))
{
var users = await _context.Users.ToListAsync();
return View(users);
}
#else
// 通常,我会使用 using 语句块来嵌套着使用 using(MiniProfiler.Current.Step("第1步"))
{ // ... 相关操作
Thread.Sleep(30); using(MiniProfiler.Current.Step("第1.1步"))
{
// ... 相关操作
Thread.Sleep(30);
} using(MiniProfiler.Current.Step("第1.2步"))
{
// ... 相关操作
Thread.Sleep(30);
}
} // 但是如果你只想分析一句话,那么使用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}\n\r Response Code:{response.StatusCode}"; if (!response.IsSuccessStatusCode)
{
throw new Exception("Error fetching data from API");
} var clickTimes = await response.Content.ReadAsStringAsync(); ViewData["clickTimes"] = clickTimes;
} return View();
}
  • 运行程序,可以看到窗口的右侧出现了http这一列:

  • 点击 http 所在列的153.1 (1),这就是使用CustomTiming分析的那段代码,它请求的URL和返回码都显示了出来。

三、案例源码:

MiniProfilerCoreDemo
 
分类: .Net Core, MVC

MiniProfiler 来分析 ASP.NET Core的更多相关文章

  1. 使用 MiniProfiler 来分析 ASP.NET Core 应用

    MiniProfiler(https://miniprofiler.com/)是一个轻量级且简单易用的分析工具库,它可以用来分析ASP.NET Core应用. 优点 针对ASP.NET Core MV ...

  2. 在WebApi项目里使用MiniProfiler并且分析 Entity Framework Core

    在WebApi项目里使用MiniProfiler并且分析 Entity Framework Core 一.安装配置MiniProfiler 在现有的ASP.NET Core MVC WebApi 项目 ...

  3. MiniProfiler性能分析工具— .Net Core中用法

    前言: 在日常开发中,应用程序的性能是我们需要关注的一个重点问题.当然我们有很多工具来分析程序性能:如:Zipkin等:但这些过于复杂,需要单独搭建. MiniProfiler就是一款简单,但功能强大 ...

  4. ASP.NET Core WebAPI中的分析工具MiniProfiler

    介绍 作为一个开发人员,你知道如何分析自己开发的Api性能么? 在Visual Studio和Azure中, 我们可以使用Application Insight来监控项目.除此之外我们还可以使用一个免 ...

  5. ASP.NET CORE MVC用时分析工具MiniProfiler

    ASP.NET CORE MVC用时分析工具MiniProfiler MiniProfiler(https://miniprofiler.com/)是一个轻量级且简单易用的分析工具库,它可以用来分析A ...

  6. 如何在ASP.NET Core Web API中使用Mini Profiler

    原文如何在ASP.NET Core Web API中使用Mini Profiler 由Anuraj发表于2019年11月25日星期一阅读时间:1分钟 ASPNETCoreMiniProfiler 这篇 ...

  7. 【ASP.NET Core】运行原理之启动WebHost

    ASP.NET Core运行原理之启动WebHost 本节将分析WebHost.CreateDefaultBuilder(args).UseStartup<Startup>().Build ...

  8. 【ASP.NET Core】运行原理[3]:认证

    本节将分析Authentication 源代码参考.NET Core 2.0.0 HttpAbstractions Security 目录 认证 AddAuthentication IAuthenti ...

  9. 【ASP.NET Core】运行原理(4):授权

    本系列将分析ASP.NET Core运行原理 [ASP.NET Core]运行原理(1):创建WebHost [ASP.NET Core]运行原理(2):启动WebHost [ASP.NET Core ...

随机推荐

  1. re正则match、search、findall、finditer函数方法使用

    match 匹配string 开头,成功返回Match object, 失败返回None,只匹配一个. search 在string中进行搜索,成功返回Match object, 失败返回None, ...

  2. Python编写的ssh客户端[类似putty]

    转载请注明出处:http://blog.csdn.net/jmppok/article/details/17588381 windows下可以通过putty以ssh方式连接linux主机.但putty ...

  3. createTextRange 创建文本对象

    document.body.createTextRange 主要是用来对一些文本对象进行操作.比如你有一大段文字,都在同一个P标签内,但是你只希望通过JS改变其中的一小部分,这时就可以用createT ...

  4. BZOJ 3672: [Noi2014]购票 树上CDQ分治

    做这道题真的是涨姿势了,一般的CDQ分治都是在序列上进行的,这次是把CDQ分治放树上跑了~ 考虑一半的 CDQ 分治怎么进行: 递归处理左区间,处理左区间对右区间的影响,然后再递归处理右区间. 所以, ...

  5. 使用terraform v0.12 生成gitlab repo 创建部署tf 文件

      以前写过一个使用模版引擎+ rest 接口的模式,生成tf 文件,v0.12 直接提供了方便的json 处理函数 我们可以直接结合http 以及templatefile providers 方便的 ...

  6. ASP复古随机验证码

    <% Call Com_CreatValidCode("ValidCode") Sub Com_CreatValidCode(pSN) Response.Expires = ...

  7. C Primer Plus--C预处理器和C库(1)

    目录 预处理符号 明显常量 #define 编译程序之前,先由预处理器检查程序(因此称为预处理器).根据程序中使用的预处理器指令,预处理用符号缩略语所代表的内容替换程序中的缩略语. 预处理器可以根据你 ...

  8. mysql left()函数

    mysql> select * from test; +----+------------+-------+-----------+ | id | name | score | subject ...

  9. Alpha冲刺(4/6)

    队名:無駄無駄 组长博客 作业博客 组员情况 张越洋 过去两天完成了哪些任务 摸鱼 提交记录(全组共用) 接下来的计划 沟通前后端成员,监督.提醒他们尽快完成各自的进度 学习如何评估代码质量 准备Al ...

  10. 刷题3:给定一个数组 nums,判断 nums 中是否存在三个下标 a,b,c数相加等于targe且a,b,c不相等

    题目: 给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,下标 ,a ,b , c 对应数相加等于 targe 找出所有满足条件且不重复的三元组下标 解析: ...