Home > Software design >  How to redirect unknown routes to 404 page in .NET Razor Pages?
How to redirect unknown routes to 404 page in .NET Razor Pages?

Time:08-25

In my application I have 3 group of pages with 3 route patterns.

  1. Pages with one url part after path like:

{domain}/en/about-us/

There is no route parameter on top of these pages right after @page.

  1. Pages with two url parts after path like:

{domain}/en/product/{permalink}/

There is an id as a route parameter on top of this page right after @page.

@page "{id}/"

  1. Pages with 3 url parts after path like:

{domain}/en/{category-permalink1}/{subcategory-permalink2}/{subsubcategory-permalink3}/

Parameters on top of this page are like below:

@page "/{maincat}/{subcat?}/{subsubcat?}/"

Everything is ok but when another part added to URL, it won't redirects to not-found page.

The question is where I can handle this redirection?

As I tried to do:

public class RouteValueRequestCultureProvider : IRequestCultureProvider
{
    private readonly CultureInfo[] _cultures;

public RouteValueRequestCultureProvider(CultureInfo[] cultures)
{
    _cultures = cultures;
}

/// <summary>
/// get {culture} route value from path string, 
/// </summary>
/// <param name="httpContext"></param>
/// <returns>ProviderCultureResult depends on path {culture} route parameter, or default culture</returns>
public Task<ProviderCultureResult> DetermineProviderCultureResult(HttpContext httpContext)
{
    var defaultCulture = "en";

    var path = httpContext.Request.Path;
    var routeValues = httpContext.Request.Path.Value.Split('/');
    var pathParts = routeValues.Where(p => !string.IsNullOrEmpty(p)).ToArray();

    if (pathParts.Length > 4)
    {
        httpContext.Response.StatusCode = 404;
        httpContext.Response.Redirect("/en/not-found/", true);
    }

    return Task.FromResult(new ProviderCultureResult(routeValues[1]));
}

}

But for URLs more than 4 parts like:

{domain}/{language_code}/{part2}/{part3}/{part4}/{part5}

Redirects to page with 404 status page that is not application's handled 404 page.

enter image description here

CodePudding user response:

Here is an answer for similar issue: Link

app.Use(async (ctx, next) =>
{
    await next();

    if(ctx.Response.StatusCode == 404 && !ctx.Response.HasStarted)
    {
        //Re-execute the request so the user gets the error page
        string originalPath = ctx.Request.Path.Value;
        ctx.Items["originalPath"] = originalPath;
        ctx.Request.Path = "/error/404";
        await next();
    }
});

Make sure to add this before app.UseEndpoints as mentioned in the original answer.

  • Related