在我的 .Net Blazor 服務器應用程式中,我希望在出現未處理的例外時向用戶顯示一個錯誤頁面。但我似乎無法顯示此錯誤頁面。為了讓它顯示出來,我添加了一個按鈕,它只是拋出一個Exception(我也嘗試過強制 a DivideByZeroException),但我沒有UseExceptionHandler選擇它,而是在我的除錯輸出中得到一個未處理的例外(在沒有除錯的情況下運行它只會凍結頁面)。我的中間件配置層次結構似乎已簽出。如果我只輸入 url, localhost:[port]/Error,我會進入錯誤頁面。
我錯過了什么?
啟動.cs
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseExceptionHandler("/Error");
app.UseHsts();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
錯誤.cshtml
@page
@model Presentation.WebUI.Pages.ErrorModel
<!DOCTYPE html>
<html>
[...html...]
</html>
錯誤.cshtml.cs
using [...]
namespace Presentation.WebUI.Pages
{
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
[IgnoreAntiforgeryToken]
public class ErrorModel : PageModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
private readonly ILogger<ErrorModel> _logger;
public ErrorModel(ILogger<ErrorModel> logger)
{
_logger = logger;
}
public void OnGet()
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
}
}
}
uj5u.com熱心網友回復:
解決方案是將 Error.cshtml 和 Error.cshtml.cs 替換為 Blazor 組件 (.razor),并將以下組件結構添加到 MainLayout.cs 檔案:
<ErrorBoundary>
<ChildContent>
@Body
</ChildContent>
<ErrorContent Context="Exception">
<Presentation.WebUI.Pages.Error></Presentation.WebUI.Pages.Error>
</ErrorContent>
</ErrorBoundary>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/521051.html
上一篇:System.Data.SqlClient.SqlException:'關鍵字'order'附近的語法不正確。'C#桌面應用程式
