'301 Permanent Redirect with Blazor and razor page

I would like to redirect all pages which doesn't match to any pattern to homepage. Structure of the URL makes it possible with catch-all option and I can easily use NavigationManager. Unfortunately this solution is using 302 temporary redirect which is not the expected result. I would like to use 301 instead.

I am using 3 different razor pages with:

@page "/page/{slug}"
@page "/{slug}"
@page "/{*slug}"
@page "/{*slug}"
@inject NavigationManager NavigationManager

@code {

    void MethodToTriggerUrl()
    {
        NavigationManager.NavigateTo("PageToRedirect");
    }
}

this resulted into 302 redirection.

Then i tried modifing Startup.cs

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapBlazorHub();
                endpoints.MapFallbackToPage("/_Host");
                endpoints.Map("/{*slug}", HandleApiFallback);
            });

            Task HandleApiFallback(HttpContext context)
            {
                context.Response.Redirect("/");
                context.Response.StatusCode = StatusCodes.Status301MovedPermanently;
                return Task.CompletedTask;
            }

but that solution makes this mapping too greedy, even with PreferExactMatches="@true".

Any tips here?:)



Solution 1:[1]

I had the same problem. My solutions was to use the HttpContext.Response. First you need to add in the startup/program this line

builder.Services.AddHttpContextAccessor();

then you can inject the HttpContextAccessor so that you can access the response inside your page:

@inject IHttpContextAccessor httpContextAccessor

then inside the page you ca redirect

 if(condition)
 {
     httpContextAccessor.HttpContext.Response.StatusCode = 301;
     httpContextAccessor.HttpContext.Response.Redirect(url, true);
 }

this will work if the wrong URL is requested in the browser or is the first entry to your website, otherwise the response might have some content and you might get a error:'StatusCode cannot be set because the response has already started.'

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