-
Notifications
You must be signed in to change notification settings - Fork 10.5k
Description
Overview and Motivation
In Blazor, handling missing pages for SEO purposes is problematic because the default workaround neither sets the proper HTTP 404 header for servers nor simplifies client-side NotFound handling. This proposal outlines a refined API to standardize the 404 response behavior across SSR and interactive environments.
Proposed API
namespace Microsoft.AspNetCore.Components
{
public partial class NavigationManager
{
/// <summary>
/// Instructs the application to treat the current request as a 404 Not Found.
/// In Server-Side Rendering, it sets HttpContext.Response.StatusCode to 404.
/// In interactive environments, it triggers the NotFoundEvent.
/// </summary>
public virtual void NotFound()
{
// ...existing logic to set response status and raise NotFoundEvent...
}
/// <summary>
/// Event that is raised when a NotFound action is invoked in interactive scenarios.
/// </summary>
public event EventHandler<EventArgs> NotFoundEvent;
}
}Usage Examples
For SSR, calling NotFound() stops further content rendering and sets the response status:
@inject NavigationManager NavigationManager
// ...existing code...
@code {
protected override void OnInitialized()
{
NavigationManager.NotFound();
}
}In WebAssembly and interactive server scenarios, NotFound() triggers the NotFoundEvent, allowing a router to render a dedicated "Not Found" page.
Alternative Designs
Risk Considerations
If the SSR response has already been initiated, invoking NotFound() cannot alter the response header, resulting in an InvalidOperationException. Developers must ensure the method is called at the correct stage of the request lifecycle.