在WebApi項目里使用MiniProfiler並且分析 Entity Framework Core


在WebApi項目里使用MiniProfiler並且分析 Entity Framework Core

一、安裝配置MiniProfiler

在現有的ASP.NET Core MVC WebApi 項目里,通過Nuget安裝MiniProfiler

Install-Package MiniProfiler.AspNetCore.Mvc MiniProfiler.EntityFrameworkCore

當然也可以通過Nuget Package Manager可視化工具安裝

11.png

接下來就是如何配置和使用 MiniProfiler 了,總共分三步:

第一步,來到Startup.csConfigureServices方法里,添加services.AddMiniProfiler();

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<DataContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DataContext")));

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

        // 首先添加一個配置選項,用於訪問分析結果:
        services.AddMiniProfiler(options =>
        {
            // 設定彈出窗口的位置是左下角
            options.PopupRenderPosition = RenderPosition.BottomLeft;
            // 設定在彈出的明細窗口里會顯式Time With Children這列
            options.PopupShowTimeWithChildren = true;
            // 設定訪問分析結果URL的路由基地址
            options.RouteBasePath = "/profiler";
        })
        // 然后在之前的配置后邊加上AddEntityFramework():
        .AddEntityFramework();
    }

第二步,來到來到Startup.csConfigure方法里,添加app.UseMiniProfiler();

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

        // 最重要的一點是就是配置中間件在管道中的位置,一定要把它放在UseMvc()方法之前。 
        app.UseMiniProfiler();

        app.UseMvc();
    }

第三步、運行程序,一共有3個可查看分析結果相關的URL地址:

1./profiler/results-index

  • 先看results-index頁面:

12.png

它表示每次調用API的記錄結果。可以看到本次調用API的總時間為1578.4毫秒。

2./profiler/results

  • 從result-index頁面點擊鏈接進入這次API調用的詳細結果頁面,也就是result頁面:

13.png

它表示每次調用API的過程分析結果,具體到每一條SQL語句的內容和執行時間。

3./profiler/results-list

  • 再看result-list頁面:

14.png

它其實就表示每個API的所有調用記錄結果的集合。

三、案例源碼:

MiniProfilerCoreWebApiDemo


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM