2019年5月28日 星期二

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

NuGet 安裝 MiniProfiler.AspNetCore.Mvc


在 Startup.cs 上新增程式碼
  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3. services.AddMvc();
  4. #region Register the MiniProfiler services
  5. services.AddMiniProfiler(options => options.RouteBasePath = "/profiler");
  6. #endregion Register the MiniProfiler services
  7. ....
  8. }
  9. public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  10. {
  11. app.UseResponseCompression();
  12. if (env.IsDevelopment())
  13. {
  14. app.UseDeveloperExceptionPage();
  15. }
  16. #region Register the MiniProfiler
  17. app.UseMiniProfiler();
  18. #endregion Register the MiniProfiler
  19. }

在 xxxxController 新增測試碼

  1. [HttpGet]
  2. public IEnumerable Get()
  3. {
  4. string url1 = string.Empty;
  5. string url2 = string.Empty;
  6. using (MiniProfiler.Current.Step("Get方法"))
  7. {
  8. using (MiniProfiler.Current.Step("準備數據"))
  9. {
  10. using (MiniProfiler.Current.CustomTiming("SQL", "SELECT * FROM Config"))
  11. {
  12. // 模擬一個SQL查詢
  13. Thread.Sleep(500);
  14. url1 = "https://www.baidu.com";
  15. url2 = "https://www.sina.com.cn/";
  16. }
  17. }
  18. using (MiniProfiler.Current.Step("使用從數據庫中查詢的數據,進行Http請求"))
  19. {
  20. using (MiniProfiler.Current.CustomTiming("HTTP", "GET " + url1))
  21. {
  22. var client = new WebClient();
  23. var reply = client.DownloadString(url1);
  24. }
  25. using (MiniProfiler.Current.CustomTiming("HTTP", "GET " + url2))
  26. {
  27. var client = new WebClient();
  28. var reply = client.DownloadString(url2);
  29. }
  30. }
  31. }
  32. return new string[] { "value1", "value2" };
  33. }

在瀏覽器上輸入 http://localhost:port/api/xxxx 可呼叫此程式







執行完畢

在 http://localhost:port/profiler/results 可以看到 MiniProfiler












Visual Studio 2017/2019 推薦的擴充功能與更新

參考文章: 覺得 Google 的 Blogger 不太順手?透過 HTML 的 iframe 移花接木 HackMD