【问题标题】:Wire up MiniProfiler to ASP.NET Core Web API Swagger将 MiniProfiler 连接到 ASP.NET Core Web API Swagger
【发布时间】:2018-08-15 11:18:37
【问题描述】:

我发现只有this manual 描述了如何使 MiniProfiler 与 ASP.NET Web API 和 Swagger UI 一起工作,但我没有找到任何描述如何使 ASP.NET Core Web API 与 MiniProfiler 一起工作以显示结果的手册大摇大摆的用户界面。

【问题讨论】:

    标签: c# asp.net-core swagger-ui asp.net-core-webapi mvc-mini-profiler


    【解决方案1】:

    您只需要自定义 Swagger index.html 文件,就像在 documentation 中解释的那样。创建自定义 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();
    }
    

    【讨论】:

    • 好的,我已经完成了,但是自定义 HTML 是一个挑战,因为我不能在那里指定 razor 语句来呈现 MiniProfiler 视图。
    • 你不需要。我已经添加了应该添加到 HTML 文件中的确切脚本。该解决方案并不理想,因为如果您稍后更新 MiniProfiler 的版本,RenderIncludes() 方法的输出可能会发生变化,并且该解决方案将停止工作。
    • 如果你想实时渲染 MiniProfiler 包含的内容,你可以在这个 HTML 文件中添加更多的 JS 代码,它基本上向你的 API 发出 AJAX 请求,返回 MiniProfiler.Current.RenderIncludes 方法的结果跨度>
    • 如果您没有在 MiniProfiler 的选项中设置 RouteBasePath 属性,如上所示,则使用默认路径 /mini-profiler-resources/includes.js
    • 我有时会为/mini-profiler-resources/results 得到 404,所以我没有得到探查器的查询结果(偶尔会发生,没有检测到模式),但在尝试相同之后就可以了。是 MiniProfiler 的错误吗?