How to redirect to a different route in Blazor Server-side

Not exactly what you're looking for, but "a solution" nonetheless. I can't seem to find a way presently, to do something similar to Response.Redirect on the server-side, but using jsinterop, in the component you wish to be able to redirect FROM, use something like this. Note, I was curious also, and knowing this would come up for myself also, I did the following:

So based on the sample app with the server-side project template...

index.cshtml

@using Microsoft.JSInterop;

 <a href="#" class="btn btn-primary" onclick="@GoSomewhere">Go somewhere with Blazor</a>

@functions {
    protected void GoSomewhere()
    {
        RedirectTo("/FetchData");  //or any other "page" in your pages folder
    }

    public static Task<string> RedirectTo(string path)
    {
        return JSRuntime.Current.InvokeAsync<string>(
            "clientJsfunctions.RedirectTo", path);
    }    
}

then, under the wwwwroot folder, place a javascript file with this:

window.clientJsfunctions = {       
    RedirectTo: function (path) {
        window.location = path;
    }
};

Finally, in your bootstrapper file, index.html, place a refeference to this js file

<body>
    <app>Loading...</app>

    <script src="_framework/blazor.server.js"></script>

    <script src="scripts/ClientUtil.js"></script>
</body>

Even better, place methods such as the one above "RedirectTo" in a seperate class, and use this as a base class for most of your component pages.

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Blazor.Components;
using Microsoft.JSInterop;

namespace MyApp.Web.App.Shared
{
    public class MycomponentBase : BlazorComponent
    {
        public static Task<string> RedirectTo(string path)
        {
            return JSRuntime.Current.InvokeAsync<string>(
                "clientJsfunctions.RedirectTo", path);
        }
    }
}

Also, remember to put this at the top of each component @inherits MycomponentBase;

Now, you should have a "Redirect" method you can call from any component that derives from your base component class.


If you can trigger on the razor page, you can use the following:

@page "/YourPageName"
@inject NavigationManager NavigationManager

<h1>xxx</h1>
.
.
.


@code {

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

After time and time of experimenting, I found out that in server side this is working:

using Microsoft.AspNetCore.Blazor.Services;
(...)
UriHelper.NavigateTo("/route");

Granted, looks almost the same, but does the work (at least in Blazor 0.8)