Redirects in Blazor Apps

Robert McLaws
CloudNimble
Published in
1 min readSep 27, 2018

--

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:

  1. Add @using Microsoft.AspNetCore.Blazor.Services to the top of your Page.
  2. Add @inject IUriHelper uriHelper underneath your @page route declaration near the top.
  3. 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.

In my next Blazor article, I’ll tell you how to get even more out of Blazor’s built-in Dependency Injection by using a variant of the Model-View-ViewModel pattern.

--

--

Robert McLaws
CloudNimble

Founder & CEO of BurnRate (@BurnRate_io). Serial entrepreneur. Former Microsoft MVP. @dotnetfdn member. Helping founders build amazing businesses.