In my .Net Blazor server application I want an Error page to be shown to the user in case of unhandled exceptions. But I can't seem to get this error page shown. To try to get it shown I have added a button that simply throws an Exception
(I have also tried forcing a DivideByZeroException
), but instead of the UseExceptionHandler
picking this up I just get an unhandled exception in my debug output (running it without debugging just freezes the page). My middleware configuring hierarchy seems to check out. If I just type in the url, localhost:[port]/Error
, I get to the error page.
What am I missing?
Startup.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");
});
}
Error.cshtml
@page
@model Presentation.WebUI.Pages.ErrorModel
<!DOCTYPE html>
<html>
[...html...]
</html>
Error.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;
}
}
}
CodePudding user response:
The solution was to replace the Error.cshtml and Error.cshtml.cs with a Blazor component (.razor) and add the below component structure to the MainLayout.cs-file:
<ErrorBoundary>
<ChildContent>
@Body
</ChildContent>
<ErrorContent Context="Exception">
<Presentation.WebUI.Pages.Error></Presentation.WebUI.Pages.Error>
</ErrorContent>
</ErrorBoundary>