ASP.NET Core 開發人員異常頁面


UseDeveloperExceptionPage 中間件

我們談談在 Startup 類的 Configure()方法中以下代碼:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseFileServer();

    app.Run(async (context) =>
    {
     throw new Exception("您的請求在管道中發生了一些異常,請檢查。");
        await context.Response.WriteAsync("Hello World!");
    });
}

如果我們使用上面的代碼運行我們的應用程序,我們看不到異常,而是看到“來自 Default.html 頁面中的 Hello”。如果您了解 asp.net Core 請求處理管道的工作原理,那么您可能已經知道我們沒有看到我們拋出的異常的原因。

UseFileServer中間件結合了UseDefaultFilesUseStaticFiles中間件的功能。在我們之前的系列視頻中,我們在 wwwroot 文件夾中包含了一個名為default.html的默認 html 文檔。

因此,對應用程序根 URL 的請求即http://localhost:49119UseFileServer處理中間件和管道從那里反轉。因此,在我們Run()方法注冊的請求管道中的下一個中間件也無法執行,因此我們不會看到此中間件拋出的異常。

現在,如果我們向http://localhost:49119/abc.html發出請求,我們會看到異常。因為,在這種情況下,UseFileServer中間件找不到名為abc.html的文件。 它會繼續去調用管道中的下一個中間件,在我們的例子中是我們使用Run()方法注冊的中間件。此中間件拋出異常,我們按預期看到異常詳細信息。

如果您對傳統的 asp.net 有任何經驗,那么您必須非常熟悉此頁面。這類似於傳統的 asp.net 中的黃色死亡屏幕

Developer Exception頁面包含異常詳細信息 :

  • 堆棧跟蹤,包括導致異常的文件名和行號
  • Query String, Cookies 和 HTTP headers

目前,在異常頁面的“Query ”選項卡上,我們看到“無 QueryString 數據”。如果請求 URL 中有任何查詢字符串參數,如下所示,您將在“Query ”選項卡下看到它們。

http://localhost:48118/abc.html?country=person&state=islocked

自定義 UseDeveloperExceptionPage 中間件

與 ASP.NET Core 中的大多數其他中間件組件一樣,我們也可以自定義UseDeveloperExceptionPage中間件。每當您想要自定義中間件組件時,請始終記住您可能擁有相應的OPTIONS對象。那么,要自定義UseDeveloperExceptionPage中間件,

DeveloperExceptionPageOptions developerExceptionPageOptions = new DeveloperExceptionPageOptions
{
    SourceCodeLineCount = 10
};
app.UseDeveloperExceptionPage(developerExceptionPageOptions);

SourceCodeLineCount屬性指定在導致異常的代碼行之前和之后要包含的代碼行數。

UseDeveloperExceptionPage 中間件如何工作

UseDeveloperExceptionPage中間件的位置盡可能的放置在其他中間件的位置前面,因為如果管道中的后面的中間件組件引發異常,它可以處理異常並顯示Developer Exception頁面。請參考以下代碼:使用 Run()注冊的中間件后出現UseDeveloperExceptionPage()中間件方法。因此,在這種情況下,將不會顯示開發人員異常頁面。這就是它必須盡早的放置在請求處理管道的原因。

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    //app.UseFileServer();

    app.Run(async (context) =>
    {
        throw new Exception("Some error processing the request");
        await context.Response.WriteAsync("Hello World!");
    });

    if (env.IsDevelopment())
    {
        DeveloperExceptionPageOptions developerExceptionPageOptions = new DeveloperExceptionPageOptions
        {
            SourceCodeLineCount = 10
        };
        app.UseDeveloperExceptionPage(developerExceptionPageOptions);
    }
}

 

歡迎添加個人微信號:Like若所思。

歡迎關注我的公眾號,不僅為你推薦最新的博文,還有更多驚喜和資源在等着你!一起學習共同進步!


免責聲明!

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



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