Search code examples
c#.netroutesurl-routingrazor-pages

ASP.NET Razor Page - How do I redirect user if they try to access invalid URL?


I have .NET 7 asp.net razor pages app, I want when somebody types "/invalidUrl" to get redirected to 404 Not Found custom page that I created. I can't find a solution. Can somebody tell me if it's possible?

I tried to add this but it doesn't work.

builder.Services.AddRazorPages(options =>
{
    options.Conventions.AddPageRoute("/*", "/NotFound");
});

Solution

  • You can use StatusCodePages middleware to control what happens when a page is not found: https://www.learnrazorpages.com/configuration/custom-errors.

    I would recommend against redirecting someone to your customer error page. That will send a 302 response code back, You should send a 404 status code, which will tell search engines to drop the incorrect URL from their index. That will happen if you use the WithReExecute option:

    app.UseStatusCodePagesWithReExecute("/notfound");