z8018
2026-02-11 b8fb68b44c29e4667f6ea5746119413809a60a9e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
using System.Text;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using StackExchange.Profiling;
using StackExchange.Profiling.Storage;
 
namespace KH.WMS.Core.Monitoring.MiniProfiler;
 
/// <summary>
/// MiniProfiler 配置
/// </summary>
public static class MiniProfilerSetup
{
    /// <summary>
    /// 添加 MiniProfiler 服务
    /// </summary>
    public static IServiceCollection AddMiniProfilerCustom(this IServiceCollection services, IConfiguration configuration, IWebHostEnvironment environment)
    {
        var miniProfilerSettings = configuration.GetSection("MiniProfiler").Get<MiniProfilerSettings>();
        miniProfilerSettings ??= new MiniProfilerSettings();
 
        // 调用官方 MiniProfiler 的扩展方法
        services.AddMiniProfiler(options =>
        {
            options.RouteBasePath = miniProfilerSettings.RouteBasePath;
            options.PopupRenderPosition = RenderPosition.BottomLeft;
            options.PopupShowTimeWithChildren = true;
 
            // 生产环境配置
            if (!miniProfilerSettings.EnableInProduction && !environment.IsDevelopment())
            {
                options.ShouldProfile = _ => false;
            }
            else
            {
                // 开发环境或配置为启用时,分析所有请求
                options.ShouldProfile = _ => true;
            }
 
            // 数据库优化
            options.TrackConnectionOpenClose = miniProfilerSettings.TrackConnectionOpenClose;
 
        });
 
        return services;
    }
 
    /// <summary>
    /// 使用 MiniProfiler 中间件
    /// </summary>
    public static IApplicationBuilder UseMiniProfilerCustom(this IApplicationBuilder app)
    {
        app.UseMiniProfiler();
        return app;
    }
}
 
/// <summary>
/// MiniProfiler 配置选项
/// </summary>
public class MiniProfilerSettings
{
    /// <summary>
    /// 路由基础路径
    /// </summary>
    public string RouteBasePath { get; set; } = "/profiler";
 
    /// <summary>
    /// 是否在生产环境启用
    /// </summary>
    public bool EnableInProduction { get; set; } = false;
 
    /// <summary>
    /// 是否跟踪数据库连接
    /// </summary>
    public bool TrackConnectionOpenClose { get; set; } = true;
 
    /// <summary>
    /// 堆栈跟踪长度
    /// </summary>
    public int StackTraceLength { get; set; } = 5;
}