日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

ASP.NET?Core處理錯誤環境_實用技巧

作者:暗斷腸 ? 更新時間: 2022-06-08 編程語言

1.前言

ASP.NET Core處理錯誤環境區分為兩種:開發環境和非開發環境。

  • 開發環境:開發人員異常頁。
  • 非開發環境:異常處理程序頁、狀態代碼頁。

在Startup.Configure方法里面我們會看到如下代碼:

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

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

2.開發人員異常頁

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

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

開發人員異常頁僅當應用程序在開發環境中運行時才會啟用,而且調用UseDeveloperExceptionPage要配置于任何要捕獲其異常的中間件前面。
該頁包括關于異常和請求的以下信息:

  • 堆棧跟蹤
  • 查詢字符串參數(如果有)
  • Cookie(如果有)
  • request header

3.異常處理程序頁

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

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("\r\n");
            await context.Response.WriteAsync("ERROR!

\r\n"); var exceptionHandlerPathFeature = context.Features.Get(); // 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!

\r\n"); } await context.Response.WriteAsync("Home
\r\n"); await context.Response.WriteAsync("\r\n"); await context.Response.WriteAsync(new string(' ', 512)); // IE padding }); }); app.UseHsts(); }

4.狀態代碼頁

一般情況下,ASP.NET Core應用程序不會為HTTP狀態代碼(如“404-未找到”)提供狀態代碼頁的。但若要提供狀態代碼頁,可以使用狀態代碼頁中間件。

4.1 UseStatusCodePages中間件

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

app.UseStatusCodePages();

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

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鏈接去了,并顯示:

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

原文鏈接:https://www.cnblogs.com/wzk153/p/10950702.html

欄目分類
最近更新