ASP.NET Core – Handle Error on Razor Page

created at 10-25-2021 views: 21

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())

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.


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;
created at:10-25-2021
edited at: 10-25-2021: