前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >Net8_WebAPI性能监控-MiniProfiler与Swagger集成

Net8_WebAPI性能监控-MiniProfiler与Swagger集成

作者头像
郑子铭
发布2024-12-09 12:44:43
发布2024-12-09 12:44:43
8200
代码可运行
举报
运行总次数:0
代码可运行

要在.NET Core项目中集成MiniProfiler和Swagger,可按照以下步骤操作:

  1. 1. 安装NuGet包
    • • 安装MiniProfiler.AspNetCore.Mvc包以集成MiniProfiler。
    • • 安装MiniProfiler.EntityFrameworkCore包以监控EF Core生成的SQL语句(可选)。
代码语言:javascript
代码运行次数:0
复制
    <PackageReference Include="MiniProfiler.AspNetCore.Mvc" Version="4.3.8" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
  1. 1. 配置服务
    • • 在Startup.cs的ConfigureServices方法中添加MiniProfiler服务配置:
代码语言:javascript
代码运行次数:0
复制
services.AddMiniProfiler(options =>
{
    options.RouteBasePath = "/profiler";
})
.AddEntityFramework();
  • • 在Configure方法中启用MiniProfiler中间件,确保它在UseEndpoints方法之前被调用:
代码语言:javascript
代码运行次数:0
复制
app.UseMiniProfiler();
  1. 1. 配置Swagger UI
    • • 下载自定义的Swagger UI页面(例如从GitHub上的xuke353/swaggerui项目,参考:https://www.cnblogs.com/xuke/p/13847248.html )并将其放置在API项目的根目录下,设置文件属性为“嵌入的资源”。
    • • 修改Startup.cs中的UseSwaggerUI中间件配置,使用自定义的index.html文件:
代码语言:javascript
代码运行次数:0
复制
app.UseSwaggerUI(c =>
{
    c.IndexStream = () => GetType().GetTypeInfo().Assembly.GetManifestResourceStream("YourNamespace.index.html");
    c.RoutePrefix = string.Empty;
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
  • • 确保替换YourNamespace为你的项目命名空间。
  1. 1. 获取MiniProfiler HTML代码片段
    • • 在一个控制器中添加一个方法来获取MiniProfiler的HTML代码片段:
代码语言:javascript
代码运行次数:0
复制
[HttpGet]
public IActionResult GetCounts()
{
    var html = MiniProfiler.Current.RenderIncludes(_accessor.HttpContext);
    return Ok(html.Value);
}
  • • 你也可以通过断点调试来获取这段HTML代码。
代码语言:javascript
代码运行次数:0
复制
public IEnumerable<WeatherForecast> GetAll2()
{
    using (MiniProfiler.Current.Step("获取成功后,开始处理最终数据"))
    {
        // 一些逻辑... 
        using (MiniProfiler.Current.Step("准备数据"))
        {
            using (MiniProfiler.Current.CustomTiming("SQL", "SELECT * FROM Config"))
            {
                // 模拟一个SQL查询
                Thread.Sleep(500); 
            }
        }

    }
    var datas = Enumerable.Range(1, 5).Select(index => new WeatherForecast
    {
        Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
        TemperatureC = Random.Shared.Next(-20, 55),
        Summary = Summaries[Random.Shared.Next(Summaries.Length)]
    });

    return datas;
}
  1. 1. 将HTML代码片段添加到Swagger UI
    • • 将获取到的HTML代码片段粘贴到自定义的Swagger UI的index.html文件的顶部。

会出现流访问异常,就是不能再开个swagger进行访问 An unhandled exception occurred while processing the request. ArgumentException: Stream was not readable. System.IO.StreamReader..ctor(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize, bool leaveOpen)

解决方法

代码语言:javascript
代码运行次数:0
复制
 app.UseSwaggerUI(c => {
c.InjectJavascript("/custom.js");
    }

然后再wwwroot文件夹下创建 custom.js,将生成的Javascript进行更改即可

custom.js

代码语言:javascript
代码运行次数:0
复制
// 等待 DOM 完全加载
document.addEventListener('DOMContentLoaded', function () {
    // 创建一个新的 script 元素
    var newScript = document.createElement('script');

    // 设置 script 的属性
    newScript.async = true; // 设置为异步加载
    newScript.id = 'mini-profiler'; // 设置 ID
    newScript.src = '/profiler/includes.min.js?v=4.3.8+1120572909'; // 设置脚本的源文件路径
    newScript.setAttribute('data-version', '4.3.8+1120572909');
    newScript.setAttribute('data-path', '/profiler/');
    newScript.setAttribute('data-current-id', '551f7bde-3d0b-4fe1-8cef-c6945f6f4d58');
    newScript.setAttribute('data-ids', 'a264a19a-395d-4e61-970f-6249ab868614,d26da3fb-eca3-4ada-899b-e85058c6010b,8dc76f68-5c1c-495d-95d0-5f07258aacf1,70f16caa-76de-4cd0-a957-82849d471053,41628017-8871-4b2a-af0c-5dfc2a6424cd,51df7af6-93ee-44b1-ba70-97920acbd3b9,4cee7860-8154-4897-81d7-7436c7408778,ba92e686-e4e3-4af6-8329-3c14645998b8,dbe17478-119b-49e3-bd4b-a83fe182354d,551f7bde-3d0b-4fe1-8cef-c6945f6f4d58');
    newScript.setAttribute('data-position', 'Left');
    newScript.setAttribute('data-scheme', 'Light');
    newScript.setAttribute('data-authorized', 'true');
    newScript.setAttribute('data-max-traces', '15');
    newScript.setAttribute('data-toggle-shortcut', 'Alt+P');
    newScript.setAttribute('data-trivial-milliseconds', '2.0');
    newScript.setAttribute('data-ignored-duplicate-execute-types', 'Open,OpenAsync,Close,CloseAsync');

    // 将 script 元素添加到文档的 head 中
    document.head.appendChild(newScript);
});
  1. 1. 启动项目
    • • 启动项目后,Swagger文档页面的左上角会出现一个小面板,当请求接口之后,会显示出当前请求的分析数据,包括接口耗时和SQL语句。

注意事项:

  • • 确保IHttpContextAccessor接口在Startup.cs中进行了注册,并且通过依赖注入获取了HttpContextAccessor对象。

代码获取

https://gitee.com/Pridejoy/PublicCode/tree/master/MiniProfilerSwaggerDemo

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2024-12-08,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 DotNet NB 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 解决方法
  • 代码获取
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档