
专为ASP.NET Core Web Apps & Web APIs设计,支持: ✅ 全链路性能监控:数据库查询、API端点、业务逻辑等关键环节 ✅ 可视化分析:请求执行时间分布、数据库耗时统计 ✅ 瓶颈热力图:直观呈现性能低下代码段
dotnet new webapi -n MyWebApi
cd MyWebApidotnet add package MiniProfiler.AspNetCore
dotnet add package MiniProfiler.AspNetCore.Mvc
dotnet add package Dapper
dotnet add package System.Data.SqlClient创建数据库及表结构
CREATE DATABASE [products_db];
CREATE TABLE [dbo].[Users](
[Id] [int] IDENTITY(,) NOT NULL,
[Name] [nvarchar]() NULL,
[Email] [nvarchar]() NULL
);定义数据模型
public class SqlUser
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
} 配置数据库连接 (appsettings.json)
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=products_db;User Id=sa;Password=smicr@123;TrustServerCertificate=True;"
}创建Dapper上下文
public classDapperContext
{
privatereadonly IConfiguration _configuration;
privatereadonlystring _connectionString;
public DapperContext(IConfiguration configuration)
{
_configuration = configuration;
_connectionString = _configuration.GetConnectionString("DefaultConnection");
}
public IDbConnection CreateConnection()
{
returnnew SqlConnection(_connectionString);
}
} 定义接口
public interface IMyService
{
Task<IEnumerable<SqlUser>> GetUsersAsync();
} 实现服务类
public classMyService : IMyService
{
privatereadonly DapperContext _dapperContext;
public MyService(DapperContext dapperContext)
{
_dapperContext = dapperContext;
}
publicasync Task<IEnumerable<SqlUser>> GetUsersAsync()
{
usingvar connection = _dapperContext.CreateConnection();
returnawait connection.QueryAsync<SqlUser>("SELECT * FROM Users");
}
} using StackExchange.Profiling;
var builder = WebApplication.CreateBuilder(args);
// 注册MiniProfiler服务
builder.Services.AddMiniProfiler(options =>
{
options.RouteBasePath = "/profiler"; // 分析器路由基址
options.PopupShowTimeWithChildren = true; // 子操作时间显示
});
// 其他服务配置
builder.Services.AddControllers();
var app = builder.Build();
// 使用性能分析中间件
app.UseMiniProfiler();
// 其他中间件
app.UseAuthorization();
app.MapControllers();
app.Run(); using Microsoft.AspNetCore.Mvc;
using StackExchange.Profiling;
namespaceMyWebApi.Controllers;
[ApiController]
[Route("[controller]")]
publicclassSampleController : ControllerBase
{
privatereadonly IMyService _myService;
public SampleController(IMyService myService)
{
_myService = myService;
}
[HttpGet]
public IActionResult Get()
{
// 开始代码段性能分析
using (MiniProfiler.Current.Step("Fetch Data"))
{
var data = _myService.GetData();
return Ok(data);
}
}
} {
"https":{
"commandName":"Project",
"dotnetRunMessages":true,
"launchBrowser":true,
"launchUrl":"swagger",
"applicationUrl":"https://localhost:5001;http://localhost:5000",
"environmentVariables":{
"ASPNETCORE_ENVIRONMENT":"Development"
}
}
}完成配置后,访问以下地址查看性能分析界面:
• API调用分析:http://localhost:5000/profiler/results
• 交互式详情:浏览器访问API后自动弹出性能报告
MiniProfiler作为.NET性能分析领域的标杆工具,通过: ✅ 实时热图分析:快速定位数据库查询、API响应等耗时操作 ✅ 代码级诊断:精确到具体方法/数据库操作的耗时统计 ✅ 可视化报告:生成性能优化建议报告
开发者可借此: 🔹 提升应用响应速度:识别并优化慢查询、冗余计算 🔹 优化资源利用:减少数据库连接池争用 🔹 提升用户体验:确保关键业务路径的高效执行