Skip to content

[Blazor] Add NavigationManager.GetUriWithHash() #53499

@MackinnonBuck

Description

@MackinnonBuck

Background and Motivation

Relative hash URLs get resolved relative to the document's baseURI, just like other relative links. This is fine if the document's baseURI matches its location (as is the case when a <base> element is not used), but it makes things inconvenient when the baseURI and location don't match.

For example, the following works when no <base> element exists, but doesn't work if the <head> were to contain something like <base href="/subidr/">.

@page "/home"

<a href="#section-1">Go to section 1</a>
...
<h1 id="section-1">Section 1</h1>

A NavigationManager.GetUriWithHash() API could help mitigate this issue:

@page "/home"
@inject NavigationManager Nav

<a href="@(Nav.GetUriWithHash("section-1"))">Go to section 1</a>
...
<h1 id="section-1">Section 1</h1>

Proposed API

namespace Microsoft.AspNetCore.Components;

public static class NavigationManagerExtensions
{
+  public static string GetUriWithHash(this NavigationManager navigationManager, string? hash);
}

Usage Examples

@page "/home"
@inject NavigationManager Nav

<a href="@(Nav.GetUriWithHash("section-1"))">Go to section 1</a>
...
<h1 id="section-1">Section 1</h1>

Alternative Designs

None considered yet.

Risks

None.

Metadata

Metadata

Assignees

Labels

api-suggestionEarly API idea and discussion, it is NOT ready for implementationarea-blazorIncludes: Blazor, Razor Componentscopilot-candidate

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions