url-routingblazorrelative-url

Blazor retrieve relative url


I am looking to retrieve the relative part of the current Blazor page URL.

For example if I am currently on https://www.mywebsite.com/someoverview, I wish to retrieve /someoverview.


Solution

  • It's not Blazor specific, we have the Uri class:

    var uri = new Uri(@"https://www.mywebsite.com/someoverview");
    var relativePath = uri.LocalPath;  // or .PathAndQuery
    

    or for the current Blazor page:

    @inject NavigationManager Navigator
    
    <a href="@Navigator.ToBaseRelativePath(Navigator.Uri)">here</a>
    

    but do note that ToBaseRelativePath() does not include a leading /, it is different from LocalPath. You can mix & match.