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");
});
CodePudding user response:
@Viktor I think all you need isto use RedirectToPage helper method.
For example
return RedirectToPage("Errors/Error404");
And you also need to change:
public void OnGet()
To
public IActionResult OnGet()
CodePudding user response:
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");