iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🚀

How to Implement Forced Redirect in Blazor [C#]

に公開
2026/02/03

For example, you might want to implement a forced redirect within a Blazor application based on specific conditions, such as forcing a redirect to an initial settings page after user login.
In this case, you want the user to be redirected to the specified page no matter which page they try to open.
I couldn't find a direct description of how to do this in my research, so I tried several methods.[1]

Requirements

  • Navigate to a specific page no matter which page is opened
  • Show a warning when trying to move from the specific page to another page and cancel the navigation
  • Can toggle On/Off
  • Keep it simple

Trying it out

Let's try.

We'll prepare a service called FooBarService with a Check method that determines whether a redirect is needed.

public class FooBarService
{
    public bool Enabled { get; set; } = false;
    public bool Check()
    {
        // Implement logic to determine if redirect is needed
        return Enabled;
    }
}

Method 1: Attempt Redirect with Middleware

This is an ASP.NET style approach. Simply attempt redirect with middleware.

public class FooBarRedirectMiddleware(FooBarService service) : IMiddleware
{
    private const string RedirectPath = "/setting";
    public async Task InvokeAsync(HttpContext context, RequestDelegate next)
    {
        // Determine if redirect is needed
        var isRedirectNeeds = service.Check();
        // Whether already on the redirect target page
        var alreadyEntered = context.Request.Path.Equals(
            RedirectPath,
            StringComparison.OrdinalIgnoreCase
        );
        if(isRedirectNeeds && !alreadyEntered)
        {
            context.Response.Redirect(RedirectPath);
        }
        await next(context);
    }
}

Register it in Program.cs:

// Programs.cs
builder.Service.AddScoped<FooBarService>();

app.UseAntiforgery();
app.MapStaticAssets();
app.MapControllers();

app.UseMiddleware<FooBarRedirectMiddleware>();
app.MapRazorComponents<App>().AddInteractiveServerRenderMode();

await app.RunAsync();

The result...

All requests for static files (js, css) were also redirected, causing the application not to work correctly!

I thought the middleware order wouldn't affect static files, but...
For now, I give up on this method.

Method 2: Attempt Redirect with EndpointFilter

I asked GitHub Copilot, and it suggested implementing with an EndpointFilter for Razor components.
So let's try it.

public class FooBarRedirectFilter : IEndpointFilter
{
    private const string RedirectPath = "/setting";
    public async ValueTask<object?> InvokeAsync(
        EndpointFilterInvocationContext context,
        EndpointFilterDelegate next
    )
    {
        // To use a scoped service, retrieve it from the Context
        var http = context.HttpContext;
        var service = http.RequestServices.GetRequiredService<FooBarService>();
        var isRedirectNeeds = service.Check();
        var alreadyEntered = http.Request.Path.Equals(
            RedirectPath,
            StringComparison.OrdinalIgnoreCase
        );
        if(isRedirectNeeds && !alreadyEntered)
        {
            http.Response.Redirect(RedirectPath);
        }
        return await next(context);
    }
}

Register it in Program.cs:

// Programs.cs
builder.Service.AddScoped<FooBarService>();
// Don't forget to add this
builder.Service.AddSingleton<FooBarRedirectFilter>();

app.UseAntiforgery();
app.MapStaticAssets();
app.MapControllers();

app.MapRazorComponents<App>()
    .AddInteractiveServerRenderMode()
    .AddEndpointFilter<RazorComponentsEndpointConventionBuilder, FooBarRedirectFilter>();

await app.RunAsync();

The result...

It doesn't work! I'm not even sure if this is the right use case (no documentation found!).

Method 3: Determine and Redirect within a Component

After all, the simplest and most reliable approach seems to be determining and redirecting within a component.

Create a component called ForceRedirect.razor that handles the redirect determination and execution.

@inject SampleSettingService Service
@inject NavigationManager Navigation
@inject IDialogService DialogService
@implements IDisposable
@code {
    // The URL to redirect to
    private const string RedirectUrl = "/setting";
    private IDisposable? registration;

    protected override async Task OnInitializedAsync()
    {
        await CheckAndRedirectIfNeeded();
    }

    protected override void OnAfterRender(bool firstRender)
    {
        if(firstRender)
        {
            registration = Navigation.RegisterLocationChangingHandler(OnLocationChanging);
        }
    }

    // Check the current URL on initial load (e.g., on reload) and redirect if necessary
    private async Task CheckAndRedirectIfNeeded()
    {
        var flag = await CheckIfRedirectNeeded(Navigation.Uri);
        if(flag)
        {
            Navigation.NavigateTo(RedirectUrl);
        }
    }

    // Check the target URL each time navigation occurs, and prevent navigation if needed
    private async ValueTask OnLocationChanging(LocationChangingContext context)
    {
        // Ignore if the current page is not the target page
        var currentFlag = await CheckIfRedirectNeeded(Navigation.Uri);
        var targetFlag = await CheckIfRedirectNeeded(context.TargetLocation);
        if(!currentFlag && targetFlag)
        {
            context.PreventNavigation();
            // Show a message to be user-friendly
            // This is an example using MudBlazor's DialogService
            await DialogService.ShowMessageBox(new()
            {
                Title = "Redirect Notice",
                Message = "You are being redirected to the settings page to update your configuration.",
                YesText = "OK"
            });

        }
    }

    // Determine if a redirect is needed
    private async Task<bool> CheckIfRedirectNeeded(string targetUrl)
    {
        // Whether the redirect is enabled in settings
        var isRedirectNeeds = await Service.Check();
        // Whether already on the redirect target page
        var alreadyOnRedirectPage = targetUrl.EndsWith(RedirectUrl, StringComparison.OrdinalIgnoreCase);
        return isRedirectNeeds && !alreadyOnRedirectPage;
    }

    public void Dispose()
    {
        registration?.Dispose();
    }
}

Then just place this component in MainLayout.razor (or anywhere appropriate):

 @inherits LayoutComponentBase
 
 <MudThemeProvider Theme="@_theme" IsDarkMode="_isDarkMode" />
 <MudPopoverProvider />
 <MudDialogProvider />
 <MudSnackbarProvider />
 <MudLayout>
     @* ... omitted ... *@
 </MudLayout>
+<ForceRedirect />

I also created a mock login page for testing:

@page "/login"

<MudButton Class="mt-3" Variant="Variant.Filled" Color="Color.Primary" OnClick="OnClick">
    Log in (dummy)
</MudButton>

@inject SampleSettingService Service
@inject NavigationManager Navigation
@code {
    private void OnClick()
    {
        // For example, after login, enable the forced redirect
        Service.ForceRedirectEnabled = true;
        Navigation.NavigateTo("/", forceLoad: true);
    }
}

The result...

It seems to work!

Summary

It feels a bit anti-climactic to end up doing it in the component, but it achieved the desired behavior, so I'll take it.

The code is available here:
https://github.com/arika0093/BlazorForceRedirectSample

脚注
  1. There are plenty of examples for redirecting when not authenticated, but that can be done with AuthorizeView etc., so it's a bit different. ↩︎

GitHubで編集を提案

Discussion