WebAPI性能監控-MiniProfiler與Swagger集成

MiniProfiler 是一款性能分析的輕量級程序,能夠基於action(request)記錄每一個階段的耗時時長,仍是能夠顯示訪問數據庫時的SQL等。html

企鵝號:877617006git

本篇主要介紹.Net Core 3.1下如何使用Swagger集成MiniProfiler來對咱們的WebAPI接口進行監控。github

安裝Nuget

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

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

配置

在startup.cs 中配置服務ConfigureServicesjson

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

激活中間件,啓用MiniProfiler服務,放在UseEndpoints方法以前。app

app.UseMiniProfiler();

配置Swagger頁面

  1. 先下載自定義Swagger頁面 https://github.com/xuke353/swaggerui/blob/master/index.html
    將該文件放到API層的根目錄下,設置文件屬性爲【嵌入的資源】
    生成操做.png
    在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輸出一下就能夠了。async

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

HTML代碼片斷.jpg
你也能夠將var html = MiniProfiler.Current.RenderIncludes(_accessor.HttpContext);隨便找個地方寫一下,而後經過斷點的方式獲取html代碼片斷。
script.jpg
而後咱們將生成的內容拷貝出來粘貼在Swagger的index.html頂部性能

<!-- HTML for static distribution bundle build -->
<script async="async" id="mini-profiler" src="/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文檔頁面的左上角就出現了一個小的面板,當請求接口以後,會顯示出當前請求的分析數據。(若是項目啓動後,左上角小面板沒出來,點請求接口後就會出來了)
MiniProfiler.png
這樣咱們就能夠查看咱們接口的耗時及SQL了。這裏的SQL仍是爲咱們拼接好參數的,很是的方便。ui

注意事項

  1. 不要在網上隨便找個MiniProfiler的HTML代碼片斷就拷貝到index.html中使用,這樣是不會成功的,由於拷貝來的的版本號和咱們所引用Nuget的版本號並不一致。
  2. MiniProfiler.Current.RenderIncludes(_accessor.HttpContext)中的_accessor.HttpContext是經過依賴注入IHttpContextAccessor接口獲取的。IHttpContextAccessor須要在Startup.cs中進行註冊。

依賴注入code

private readonly IHttpContextAccessor _accessor;
public ChartController(IHttpContextAccessor accessor) {
   _accessor = accessor;
}

在Startup.cs中將IHttpContextAccessor注入容器

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();