2019年5月28日 星期二

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

NuGet 安裝 MiniProfiler.AspNetCore.Mvc


在 Startup.cs 上新增程式碼


public void ConfigureServices(IServiceCollection services)
{
 services.AddMvc();


 #region Register the MiniProfiler services

 services.AddMiniProfiler(options => options.RouteBasePath = "/profiler");

 #endregion Register the MiniProfiler services
 
 ....
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
 app.UseResponseCompression();

 if (env.IsDevelopment())
 {
  app.UseDeveloperExceptionPage();
 }


 #region Register the MiniProfiler

 app.UseMiniProfiler();

 #endregion Register the MiniProfiler

}


在 xxxxController 新增測試碼



[HttpGet]
public IEnumerable Get()
{
 string url1 = string.Empty;
 string url2 = string.Empty;
 using (MiniProfiler.Current.Step("Get方法"))
 {
  using (MiniProfiler.Current.Step("準備數據"))
  {
   using (MiniProfiler.Current.CustomTiming("SQL", "SELECT * FROM Config"))
   {
    // 模擬一個SQL查詢
    Thread.Sleep(500);

    url1 = "https://www.baidu.com";
    url2 = "https://www.sina.com.cn/";
   }
  }


  using (MiniProfiler.Current.Step("使用從數據庫中查詢的數據,進行Http請求"))
  {
   using (MiniProfiler.Current.CustomTiming("HTTP", "GET " + url1))
   {
    var client = new WebClient();
    var reply = client.DownloadString(url1);
   }

   using (MiniProfiler.Current.CustomTiming("HTTP", "GET " + url2))
   {
    var client = new WebClient();
    var reply = client.DownloadString(url2);
   }
  }
 }
 return new string[] { "value1", "value2" };
}


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







執行完畢

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












沒有留言:

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

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