Roman Pokrovskij
Roman Pokrovskij

Reputation: 9776

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?
        {
           //...
        }
     }
 }

Upvotes: 3

Views: 2810

Answers (1)

Nkosi
Nkosi

Reputation: 247413

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

Upvotes: 5

Related Questions