MiniProfiler 是一款性能分析的輕量級程式,可以基于action(request)記錄每個階段的耗時時長,還是可以顯示訪問資料庫時的SQL等,
企鵝號:877617006
本篇主要介紹.Net Core 3.1下如何使用Swagger集成MiniProfiler來對我們的WebAPI介面進行監控,
安裝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頁面
- 先下載自定義Swagger頁面 https://github.com/xuke353/swaggerui/blob/master/index.html,
將該檔案放到API層的根目錄下,設定檔案屬性為【嵌入的資源】

在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);
}

你也可以將var html = MiniProfiler.Current.RenderIncludes(_accessor.HttpContext);隨便找個地方寫一下,然后通過斷點的方式獲取html代碼片段,

然后我們將生成的內容拷貝出來粘貼在Swagger的index.html頂部
<!-- HTML for static distribution bundle build -->
<script async="async" id="mini-profiler" src="https://www.cnblogs.com/profiler/includes.min.js?v=4.2.1+b27bea37e9"
data-version="4.2.1+b27bea37e9" data-path="/profiler/"
data-current-id="142f3c02-c5d7-42e0-be9e-2a45e46d727a"
data-ids="64b457a1-275e-4bfa-9b2f-e5bd5385a80f,142f3c02-c5d7-42e0-be9e-2a45e46d727a"
data-position="Left"
data-scheme="Light"
data-authorized="true"
data-max-traces="15"
data-toggle-shortcut="Alt+P"
data-trivial-milliseconds="2.0"
data-ignored-duplicate-execute-types="Open,OpenAsync,Close,CloseAsync"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>%(DocumentTitle)</title>
........
........
重新啟動專案,Swagger檔案頁面的左上角就出現了一個小的面板,當請求介面之后,會顯示出當前請求的分析資料,(如果專案啟動后,左上角小面板沒出來,點請求介面后就會出來了)

這樣我們就可以查看我們介面的耗時及SQL了,這里的SQL還是為我們拼接好引數的,非常的方便,
注意事項
- 不要在網上隨便找個MiniProfiler的HTML代碼片段就拷貝到index.html中使用,這樣是不會成功的,因為拷貝來的的版本號和我們所參考Nuget的版本號并不一致,
- MiniProfiler.Current.RenderIncludes(_accessor.HttpContext)中的_accessor.HttpContext是通過依賴注入IHttpContextAccessor介面獲取的,IHttpContextAccessor需要在Startup.cs中進行注冊,
依賴注入
private readonly IHttpContextAccessor _accessor;
public ChartController(IHttpContextAccessor accessor) {
_accessor = accessor;
}
在Startup.cs中將IHttpContextAccessor注入容器
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/185716.html
標籤:.NET Core
