'How to show a custom 404 page instead of default by Browser? When I'm using my Razor Pages Application
If you type http://google.com/ShowMeYourCustom404Page in your browser and then press Enter
. You will be redirect to Google 404 Page.
If we apply the same concept on github https://github.com/ShowMeYourCustom404Page .It will show you:
Now if you use my Razor Page Application it will show the default one provided by the browser. But I don't want that, I want to show my custom 404 Page Error.cshtml
.
I know there is a method call RedirectToPage()
. And It can be used on this scenarios.
public IActionResult OnGet(int id) { if (id <= 0) return RedirectToPage("/Error"); return Page(); }
But i can't use `RedirectToPage()` on a page that doesn't exist. So What can i do to accomplish my goal?
Solution 1:[1]
According to your description, I suggest you could try to use custom middleware to achieve your requirement.
You could check the status codes after the next method and then modify the request path to custom error error page path.
More details, you could refer to below codes:
Custom middleware:
app.Use(async (ctx, next) =>
{
await next();
if (ctx.Response.StatusCode == 404 && !ctx.Response.HasStarted)
{
ctx.Request.Path = "/error404";
await next();
}
});
Add it into Configure method:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.Use(async (ctx, next) =>
{
await next();
if (ctx.Response.StatusCode == 404 && !ctx.Response.HasStarted)
{
ctx.Request.Path = "/error404";
await next();
}
});
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
Error404 razor page:
@page
@model RazorPageRelated.Pages.Error404Model
@{
ViewData["Title"] = "Error404";
}
<h1>Error404</h1>
Result:
Solution 2:[2]
In Startup.cs
file in method Configure
just insert following line (right after if/else for development):
app.UseStatusCodePagesWithReExecute("/Errors/{0}");
Then you can add a folder \Pages\Errors
with different pages for every statuscode, for example a 404.cshtml
. You might also remove {0}
and just create one page for everything.
Then it's used for pages, that don't exist and also for return NotFound();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Brando Zhang |
Solution 2 | Matt |