Search code examples
blazorblazor-client-side

Navigate to NotFound page if http GetById returns 404


Suppose I have the following Routing schema

  • CustomerListComponent: Containing a list of Customers
  • CustomerDetailComponent: Holding the details of a specific customer

with Routes

  • @page "customer"

  • @page "customer/{id:int}

and a Router setup as such:

<Router AppAssembly="typeof(Startup).Assembly">
    <Found Context="routeData">
        ....
    </Found>
    <NotFound>
        <p>Sorry, there's nothing at this address.</p>
    </NotFound>
</Router>

I want the page to redirect to the NotFound page, if the http call does not find the customer with the id that was passed to the URL

Inside my component right now

protected override async Task OnInitializedAsync()
{
   var customer = await CustomerService.GetById(customerId);
   if (customer == null) 
   {
      // redirect to 404 NOTFOUND         
   }
}

It seems that right now, any valid integer in the URL will open the CustomerDetail component and when it tries to show the Customer details, it will (obviously) crash with a null reference

Am I missing something obvious?

EDIT : I have tried to load a custom 404 page and handle navigation inside my http service, but this results in URL change on the browser. I want to preserve the faulty URL and still navigate to the 404 page.


Solution

  • You can use the NavigationManager

    @inject NavigationManager _nagigationManager;
    ...
    @code {
        protected override async Task OnInitializedAsync()
        {
           var customer = await CustomerService.GetById(customerId);
           if (customer == null) 
           {
              _navigationManager.NavigateTo("404page");
           }
       }
    }
    

    If you want to stay on the same page, but display the content of an error page, just add the component in your html code :

    @if(_notFound) 
    {
        <NotFoundPage />
    }
    else
    {
    ...
    }
    @code {
        private bool _notFound;
        protected override async Task OnInitializedAsync()
        {
           var customer = await CustomerService.GetById(customerId);
           if (customer == null) 
           {
              _notFound = true;
              StateHasChanged();
           }
       }
    }