在WebApi項(xiàng)目里使用MiniProfiler并且分析 Entity Framework Core

在WebApi項(xiàng)目里使用MiniProfiler并且分析 Entity Framework Core

一、安裝配置MiniProfiler

在現(xiàn)有的ASP.NET Core MVC WebApi 項(xiàng)目里,通過(guò)Nuget安裝MiniProfiler

Install-Package MiniProfiler.AspNetCore.Mvc MiniProfiler.EntityFrameworkCore

當(dāng)然也可以通過(guò)Nuget Package Manager可視化工具安裝

11.png

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

第一步,來(lái)到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);

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

第二步,來(lái)到來(lái)到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)
    {
        ...

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

        app.UseMvc();
    }

第三步、運(yùn)行程序,一共有3個(gè)可查看分析結(jié)果相關(guān)的URL地址:

1./profiler/results-index

  • 先看results-index頁(yè)面:
12.png

它表示每次調(diào)用API的記錄結(jié)果。可以看到本次調(diào)用API的總時(shí)間為1578.4毫秒。

2./profiler/results

  • 從result-index頁(yè)面點(diǎn)擊鏈接進(jìn)入這次API調(diào)用的詳細(xì)結(jié)果頁(yè)面,也就是result頁(yè)面:
13.png

它表示每次調(diào)用API的過(guò)程分析結(jié)果,具體到每一條SQL語(yǔ)句的內(nèi)容和執(zhí)行時(shí)間。

3./profiler/results-list

  • 再看result-list頁(yè)面:
14.png

它其實(shí)就表示每個(gè)API的所有調(diào)用記錄結(jié)果的集合。

三、案例源碼:

MiniProfilerCoreWebApiDemo
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容