aspnetcore: Create simpler way to show Not Found 404 UI with Blazor

Is there an existing issue for this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe the problem.

Currently, we support the lack of a page in blazor, unfortunately, if we want to place a 404 header for SEO and, for example, google bot, it creates a problem. It’s worth handling this exception. There is currently a workaround that doesn’t look very good to me.

App.razor

        <NotFound>
            <PageTitle>Not found</PageTitle>
            <LayoutView Layout="@typeof(Pages._404)">
                404
            </LayoutView>
        </NotFound>

404 layout:

@layout Shared.MainLayout
@inherits LayoutComponentBase
@using Microsoft.AspNetCore.Http

@Body

@code {
    [Inject] IHttpContextAccessor httpContextAccessor { get; set; } = null!;

    [Inject] PersistentComponentState _ApplicationState { get; set; } = null!;

    PersistingComponentStateSubscription persistingSubscription;

    bool model = true;

    protected override void OnInitialized()
    {
        persistingSubscription = _ApplicationState.RegisterOnPersisting(Task () => { _ApplicationState.PersistAsJson($"404", model); return Task.CompletedTask; });
        if (!_ApplicationState.TryTakeFromJson<bool>($"404", out var dto))
        {
            if (httpContextAccessor.HttpContext is not null)
                httpContextAccessor.HttpContext.Response.StatusCode = StatusCodes.Status404NotFound;
        }
    }
}

Also I read in the documentation that we shouldn’t use httpcontext in blazor subpages.

Describe the solution you’d like

I think Not Found blazor server side should automatically handle and ship. I’ve searched the internet and the documentation and found nothing useful.

Additional context

No response

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 17
  • Comments: 27 (8 by maintainers)

Most upvoted comments

I have encountered this challenge in my app where I am using InteractiveWebAssemblyRenderMode(prerender: false).

I wasn’t satisfied with the UseStatusCodePagesWithRedirects method because it triggers a full page refresh when a user navigates to a non-existent page through a link within the app.

To address this, I implemented a fallback page as follows: DemoApp.Client.Pages.NotFound.razor

@page "/{*route:nonfile}"
<PageTitle>404 Not Found</PageTitle>
<h1>404 Not Found</h1>
The page @Route was not found.
@code {
 [Parameter]
    public string? Route { get; set; }
}

This page serves as a fallback for invalid links within my app without triggering a full page refresh. However, for unknown URLs entered manually by the user, a full page refresh still occurs, which is expected behavior.

I believe this solution can be useful for someone facing a similar issue, although I’m not entirely sure if it is the correct approach.

@kejdajar thank you! This was the only sample code I was able to find that for Blazor Server .NET 8 will catch Route Not Found and allow the Route that wasn’t found to be captured in a Parameter for inspection and potential additional logic. I checked now, and see that route:nonfile is discussed in .NET 8 documentation but not with sample code as provided above. It appears to me this is a gap in documentation - I didn’t find a place where recommended practices for handling Not Found Routes in a common manner where logic can be applied and different responses can be invoked based on the Not Found Route. Microsoft, whatever is done in this realm for Blazor .NET [future releases] please don’t render the above solution inoperable.

Thanks for contacting us.

We’re moving this issue to the .NET 9 Planning milestone for future evaluation / consideration. We would like to keep this around to collect more feedback, which can help us with prioritizing this work. We will re-evaluate this issue, during our next planning meeting(s). If we later determine, that the issue has no community involvement, or it’s very rare and low-impact issue, we will close it - so that the team can focus on more important and high impact issues. To learn more about what to expect next and how this issue will be handled you can read more about our triage process here.

@danroth27 I noticed that the new template (VS 17.8.0 Preview 2.0) lacks custom 404 error support.

Yes, this something we still expect to address in an upcoming .NET 8 update: https://github.com/dotnet/aspnetcore/pull/50550

We should extend navigation manager with a NotFound() method. The server implementation for NotFound will use that to trigger a 404 response. The interactive versions of the framework will raise a NotFoundEvent (or similar). The router will listen to that NotFoundEvent and trigger the render of the NotFound fragment/page in interactive scenarios.

This issue is best tackled in tandem with https://github.com/dotnet/aspnetcore/issues/58815

2 major versions came, but the track “not found” in Blazor is still pending.

Could you clarify more about what doesn’t work here? I just tried adding this to a page:

    [CascadingParameter] public HttpContext HttpContext { get; set; }

    protected override async Task OnInitializedAsync()
    {
        HttpContext.Response.StatusCode = 404;
    }

… and it worked immediately. It’s also not necessary to add anything in <Router> because with SSR you already get a native ASP.NET Core 404 page if there’s no matching .razor endpoint.

@mkArtakMSFT Looks like we still have a functionality gap here that we need to discuss. #50550 didn’t actually address this scenario. There was some related discussion in #48983 about having a way to trigger a 404 response, but that work wasn’t done in https://github.com/dotnet/aspnetcore/pull/49801 either.

@kejdajar This issue #45654 has been Closed as completed in #60752. If you ever found the time, it would be awesome if you please confirm that your fix described above in this issue #45654 (i.e.: @page “/{*route:nonfile}”) continues to work the same with the latest/greatest .NET implementation. That code has been helpful to my project!

I have encountered this challenge in my app where I am using InteractiveWebAssemblyRenderMode(prerender: false). I wasn’t satisfied with the UseStatusCodePagesWithRedirects method because it triggers a full page refresh when a user navigates to a non-existent page through a link within the app. To address this, I implemented a fallback page as follows: DemoApp.Client.Pages.NotFound.razor @page “/{*route:nonfile}” 404 Not Found

404 Not Found

The page @route was not found. @code { [Parameter] public string? Route { get; set; } } This page serves as a fallback for invalid links within my app without triggering a full page refresh. However, for unknown URLs entered manually by the user, a full page refresh still occurs, which is expected behavior. I believe this solution can be useful for someone facing a similar issue, although I’m not entirely sure if it is the correct approach.

Thanks! Is there a way to return an actual 404 using this method? Because the page is still a 200 in the end. It’s very odd to me, that there aren’t any guidelines on how to implement a 404 page.

As far as I understand, if you’re using Blazor WebAssembly (especially with InteractiveWebAssemblyRenderMode(prerender: false)), all your routing is handled on the client side once the app is loaded, so the server is always returning a 200 OK for the HTML. If you really need a 404, you’d have to implement it on the server before Blazor’s client routing takes over. This is just my understanding, though—I’m not an expert.

Thanks for contacting us.

We’re moving this issue to the .NET 9 Planning milestone for future evaluation / consideration. We would like to keep this around to collect more feedback, which can help us with prioritizing this work. We will re-evaluate this issue, during our next planning meeting(s). If we later determine, that the issue has no community involvement, or it’s very rare and low-impact issue, we will close it - so that the team can focus on more important and high impact issues. To learn more about what to expect next and how this issue will be handled you can read more about our triage process here.

@danroth27 I found a workaround to show a 404 page with Blazor SSR. https://github.com/T-Smith45/Blazor-404-redirect. Not sure if it’s a proper workaround but I’m hoping some comments can be added to the default template since there’s a lack of documentation on this issue. @Alerinos not sure if this works for your use case.