ASP.NET Core – Handle Error on Razor Page

preface

The website should not have error, but it will happen, so it is very important to give users a friendly error page

 

Main reference

Handle errors in ASP.NET Core

 

Error handling during development

In dev, asp.net core has made an error page for us, which is very friendly to developers  

We don’t need to make any settings

 

 

Error handling during production

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

Useexceptionhandler will find the corresponding razor page rendering return content through path/internalservererror

In the model, we can get relevant 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 process 404

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

The 404 problem can be solved through usestatuscodepageswithreexecute. Its execution is similar to that of exception handler

Find the page according to the path and render it back. Similarly, you can get the status information in the model

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

 

Similar Posts: