Skip to content

API proposal for NotFound #61133

@javiercn

Description

@javiercn

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

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

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions