(7)ASP.NET Core 中的錯誤處理

1.前言

ASP.NET Core處理錯誤環境區分爲兩種:開發環境和非開發環境。
開發環境:開發人員異常頁。
非開發環境:異常處理程序頁、狀態代碼頁。
在Startup.Configure方法裏面咱們會看到以下代碼:html

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
       //開發環境
    } 
    else
    {
       //非開發環境
    }
}

env.IsDevelopment()是判斷應用程序運行是在開發環境仍是非開發環境,具體配置在Properties/launchSettings.json,找到ASPNETCORE_ENVIRONMENT屬性,默認值是開發環境(Development),具體環境配置知識點後面咱們再來學習下。json

2.開發人員異常頁

向Startup.Configure方法添加代碼,以當應用在開發環境中運行時啓用此頁:瀏覽器

if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}

開發人員異常頁僅當應用程序在開發環境中運行時纔會啓用,並且調用UseDeveloperExceptionPage要配置於任何要捕獲其異常的中間件前面。
該頁包括關於異常和請求的如下信息:
●堆棧跟蹤
●查詢字符串參數(若是有)
●Cookie(若是有)
●request headerapp

3.異常處理程序頁

在下面的示例中,UseExceptionHandler 在非開發環境中添加異常處理中間件:async

if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
else
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

Razor Pages應用模板提供「頁面」文件夾中的Error頁(.cshtml)和PageModel類(ErrorModel)。 對於MVC應用,項目模板包括Error操做方法和Error視圖。操做方法以下:學習

[AllowAnonymous]
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
    return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}

不要使用HTTP方法屬性(如HttpGet)修飾錯誤處理程序操做方法,由於會阻止某些請求訪問的方法。同時最好容許匿名訪問方法,以便未經身份驗證的用戶可以接收錯誤視圖。
UseExceptionHandler中間還可使用lambda進行異常處理:測試

if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
else
{
   app.UseExceptionHandler(errorApp =>
   {
        errorApp.Run(async context =>
        {
            context.Response.StatusCode = 500;
            context.Response.ContentType = "text/html";
            await context.Response.WriteAsync("<html lang=\"en\"><body>\r\n");
            await context.Response.WriteAsync("ERROR!<br><br>\r\n");
            var exceptionHandlerPathFeature = 
                context.Features.Get<IExceptionHandlerPathFeature>();
            // Use exceptionHandlerPathFeature to process the exception (for example, 
            // logging), but do NOT expose sensitive error information directly to 
            // the client.
            if (exceptionHandlerPathFeature?.Error is FileNotFoundException)
            {
                await context.Response.WriteAsync("File error thrown!<br><br>\r\n");
            }
            await context.Response.WriteAsync("<a href=\"/\">Home</a><br>\r\n");
            await context.Response.WriteAsync("</body></html>\r\n");
            await context.Response.WriteAsync(new string(' ', 512)); // IE padding
        });
    });
app.UseHsts();
}

4.狀態代碼頁

通常狀況下,ASP.NET Core應用程序不會爲HTTP狀態代碼(如「404-未找到」)提供狀態代碼頁的。但若要提供狀態代碼頁,可使用狀態代碼頁中間件。ui

4.1 UseStatusCodePages中間件

若要啓用常見錯誤狀態代碼的默認純文本處理程序,請在Startup.Configure方法中調用 UseStatusCodePages:spa

app.UseStatusCodePages();

而這裏有一點要注意的是,調用UseStatusCodePages中間件要在例如靜態文件中間件和 MVC中間件等中間件前面調用:code

app.UseStatusCodePages();
app.UseStaticFiles();
app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});

下面經過運行應用程序在瀏覽器地址欄上輸入一個不存在地址看看配置該中間件後的效果:

很顯然當咱們輸入一個不存在地址以後就會打開一個處理錯誤的狀態代碼頁。
UseStatusCodePages中間件還有兩種重載使用方法,具體運行效果就不一一截圖了,你們自行測試。
●包含格式字符串的 UseStatusCodePages:

app.UseStatusCodePages("text/plain", "Status code page, status code: {0}");

●包含lambda的UseStatusCodePages:

app.UseStatusCodePages(async context =>
{
    context.HttpContext.Response.ContentType = "text/plain";
    await context.HttpContext.Response.WriteAsync(
        "Status code page, status code: " +
        context.HttpContext.Response.StatusCode);
});

4.2 UseStatusCodePagesWithRedirect中間件

●向客戶端發送「302 - 已找到」狀態代碼。
●將客戶端重定向到URL模板中的位置。
下面咱們在Startup.Configure方法中調用UseStatusCodePagesWithRedirect:

app.UseStatusCodePagesWithRedirects("/Error/{0}");

運行應用程序在瀏覽器上輸入不存在地址https://localhost:44353/1看看配置該中間件後的效果,你會發覺當咱們輸入上述地址後會跳轉到https://localhost:44353/Error/404連接去了,並顯示:

這就說明白當咱們輸入一個不存在地址以後會重定向中間件設置的地址頁面去了。

 

參考文獻:
處理 ASP.NET Core 中的錯誤

相關文章
相關標籤/搜索