.net core WebAPI性能監控-MiniProfiler與Swagger集成

————恢復內容開始————

安裝Nuget

Install-Package MiniProfiler.AspNetCore.Mvc
Install-Package MiniProfiler.EntityFrameworkCore

MiniProfiler.EntityFrameworkCore 用來監控EF Core生成的SQL

配置

在startup.cs 中配置服務ConfigureServices

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

激活中間件,啟用MiniProfiler服務,放在UseEndpoints方法之前。

app.UseMiniProfiler();

配置Swagger頁面

  1. 先下載自定義Swagger頁面 //github.com/xuke353/swaggerui/blob/master/index.html。
    將該文件放到API層的根目錄下,設置文件屬性為【嵌入的資源】

 

  1. 在Startup.cs文件中,我們需要修改UseSwaggerUI中間件的配置
app.UseSwaggerUI(c =>
{
    c.IndexStream = () => GetType().GetTypeInfo().Assembly.GetManifestResourceStream("AdmBoots.Api.index.html");
    c.RoutePrefix = string.Empty;
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});

注意:這裡AdmBoots.Api是項目的命名空間名
當前這個時候還不能使用,我們還需要在 Swagger的index.html中進行配置,以便它能在 Swagger 中使用。
重點來了
我們首先需要獲取用於顯示MiniProfiler的html程式碼片段,隨便寫個控制器,使用MiniProfiler的API輸出一下就可以了。

[HttpGet]
public IActionResult GetCounts() {
    var html = MiniProfiler.Current.RenderIncludes(_accessor.HttpContext);
     return Ok(html.Value);
 }



————恢復內容開始————

安裝Nuget

Install-Package MiniProfiler.AspNetCore.Mvc
Install-Package MiniProfiler.EntityFrameworkCore

MiniProfiler.EntityFrameworkCore 用來監控EF Core生成的SQL

配置

在startup.cs 中配置服務ConfigureServices

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

激活中間件,啟用MiniProfiler服務,放在UseEndpoints方法之前。

app.UseMiniProfiler();

配置Swagger頁面

  1. 先下載自定義Swagger頁面 //github.com/xuke353/swaggerui/blob/master/index.html。
    將該文件放到API層的根目錄下,設置文件屬性為【嵌入的資源】

 

  2.在Startup.cs文件中,我們需要修改UseSwaggerUI中間件的配置

app.UseSwaggerUI(c =>
{
    c.IndexStream = () => GetType().GetTypeInfo().Assembly.GetManifestResourceStream("AdmBoots.Api.index.html");
    c.RoutePrefix = string.Empty;
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});

注意:這裡AdmBoots.Api是項目的命名空間名
當前這個時候還不能使用,我們還需要在 Swagger的index.html中進行配置,以便它能在 Swagger 中使用。
重點來了
我們首先需要獲取用於顯示MiniProfiler的html程式碼片段,隨便寫個控制器,使用MiniProfiler的API輸出一下就可以了。

[HttpGet]
public IActionResult GetCounts() {
    var html = MiniProfiler.Current.RenderIncludes(_accessor.HttpContext);
     return Ok(html.Value);
 }

注意事項

  1. 不要在網上隨便找個MiniProfiler的HTML程式碼片段就拷貝到index.html中使用,這樣是不會成功的,因為拷貝來的的版本號和我們所引用Nuget的版本號並不一致。
  2. MiniProfiler.Current.RenderIncludes(_accessor.HttpContext)中的_accessor.HttpContext是通過依賴注入IHttpContextAccessor介面獲取的。IHttpContextAccessor需要在Startup.cs中進行註冊。

依賴注入



 

Tags: