Redirects in Blazor Apps
While working on my latest Blazor creation, I needed a way to be able to mimic a Response.Redirect and navigate the user away from the page. Web searches were of very little help, so I did what any resourceful developer would do: I dug into the source code. What I found was a thing of beauty.
tl;dr: Use the IUriHelper
The short answer is as follows:
- Add
@using Microsoft.AspNetCore.Blazor.Services
to the top of your Page. - Add
@inject IUriHelper uriHelper
underneath your@page
route declaration near the top. - Use the
uriHelper
in a method. For example:
@functions
{
void ButtonClick()
{
uriHelper.NavigateTo("\");
}
}
Under the Covers
The secret is in Blazor’s Dependency Injection and JavaScript interop. During Blazor’s startup, it automatically injects browser interop code into the pipeline. The BrowserUriHelper
instance is then available anywhere it needs to be to let you seamlessly access the document.location
property of the DOM, but in C#. BrowserUriHelper
even has access to get the current URL, if you need to manipulate it in some way.