ASP.NET Core – Handle Error on Razor Page

created at 10-25-2021 views: 2

Error handling in the development period

At the time of dev, ASP.NET Core has already made an error page for us, which is very friendly to developers.

We don't need to make any settings.

error page

Error handling during production period

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/InternalServerError");
}

UseExceptionHandler will find the corresponding razor page rendering return content through path /InternalServerErrorr.

In Model, we can get related exception information through request features

public void OnGet()
{
    var exceptionHandlerPathFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
    RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
}

404 page

404 is not an Exception, so the above scheme will not handle 404.

app.UseStatusCodePagesWithReExecute("/Status/{0}");

The 404 problem can be solved by UseStatusCodePagesWithReExecute. Its execution is similar to Exception handler.

Find the page according to the path and render it back.You can also get the status information in the Model.

public void OnGet(string statusCode)
{
    var exceptionHandlerPathFeature = HttpContext.Features.Get<IStatusCodeReExecuteFeature>();
    RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
}
Please log in to leave a comment.