Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setup app.UseExceptionHandler with "razor page" Error.cshtml?

I have tried to replace default MVC error page Error.cshtml with my own created Error2.cshtml razor page, but this doesn't work: error 404.

What I should additionally configure in routing to get it working?

Startup.cs

app.UseExceptionHandler("/Home/Error2"); // new razor page is located in standard /Views/Shared folder

Error2Model

namespace MyApp.Views.Shared
{
    public class Error2Model : PageModel
    {
        public IActionResult OnGet() // this looks  unreliable but what to use instead?
        {
           //...
        }
     }
 }
like image 261
Roman Pokrovskij Avatar asked Aug 18 '26 16:08

Roman Pokrovskij


1 Answers

Reference Handle errors in ASP.NET Core: Configure a custom exception handling page

Configure an exception handler page to use when the app isn't running in the Development environment:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    env.EnvironmentName = EnvironmentName.Production;

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/error");
    }

In a Razor Pages app, the dotnet new Razor Pages template provides an Error page and an error PageModel class in the Pages folder.

In your case you would set it to

app.UseExceptionHandler("/error2");

which should be placed in the Pages/Error2.cshtml

Update its PageModel

namespace MyApp.Pages {
    public class Error2Model : PageModel {
        public IActionResult OnGet() {
           //...
            return Page();
        }
     }
 }
like image 62
Nkosi Avatar answered Aug 20 '26 06:08

Nkosi