将MiniProfiler与ASP.NET Core Web API Swagger相连接

12

我只找到了 这篇指南,介绍如何使用 MiniProfiler 在 ASP.NET Web API 和 Swagger UI 中运行,但是我没有找到任何关于如何让 ASP.NET Core Web API 与 MiniProfiler 配合显示结果在 Swagger UI 中的指南。

1个回答

12
你只需要按照文档中的说明自定义Swagger的index.html文件。在创建自定义HTML文件后,将以下行添加到其中:
<script async="async" id="mini-profiler" src="/profiler/includes.js?v=4.0.0.0" data-version="4.0.0.0" data-path="/profiler/" data-current-id="865f1487-f416-4d39-87fe-723e34847577" data-ids="" data-position="left" 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>

基本上,以上脚本是MiniProfiler.Current.RenderIncludes()方法的输出。

以下是ConfigureServicesConfigure方法,以查看Swagger和Miniprofiler如何配置

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    // Register the Swagger generator, defining one or more Swagger documents
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
    });

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

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseMiniProfiler();
    }

    app.UseSwagger();
    app.UseSwaggerUI(c => {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
        c.IndexStream = () => GetType().GetTypeInfo().Assembly.GetManifestResourceStream("SOMpSwaggerNetCore.SwaggerIndex.html");
    });
    app.UseMvc();
}

1
好的,我已经完成了这个任务,但是自定义HTML是一个挑战,因为我无法在那里指定剃刀语句来呈现MiniProfiler视图。 - Vadim Ovchinnikov
你不需要这样做。我已经添加了确切的脚本,应该添加到HTML文件中。这个解决方案并不理想,因为如果你稍后更新MiniProfiler的版本,RenderIncludes()方法的输出可能会改变,这个解决方案将停止工作。 - Alexey Andrushkevich
如果您想即时呈现MiniProfiler包含内容,可以向此HTML文件添加更多JS代码,该代码基本上会向您的API发出AJAX请求,该请求返回“MiniProfiler.Current.RenderIncludes”方法的结果。 - Alexey Andrushkevich
1
如果您没有按照上述示例在MiniProfiler选项中设置“RouteBasePath”属性,则请使用默认路径“/mini-profiler-resources/includes.js”。 - Alexey Andrushkevich
有时候我会在/mini-profiler-resources/results这个地址上收到404的错误,所以无法获取查询的性能分析结果(这种情况偶尔发生,没有规律可循),但是再试一次就没问题了。这是MiniProfiler的bug吗? - Vadim Ovchinnikov
我猜是这样的,ASP.NET Core的MiniProfiler是预发布包。我会在他们的GitHub上报告这个问题。 - Alexey Andrushkevich

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接