aspnetcore: Router incorrectly calls SetParametersAsync multiple times

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

WHEN I’m on /index?queryparam=abc and I click a link to /index/999 which is handled by the same component,

THEN SetParametersAsync is called twice:

  1. With QueryParam=null
  2. With Id=999, QueryParam=“abc”
      OnNavigateAsync to 'index?queryparam=abc'
      SetParametersAsync Id:0, QueryParam:abc

      OnNavigateAsync to 'index/999'
      SetParametersAsync Id:0, QueryParam:
      SetParametersAsync Id:999, QueryParam:

This is causing a lot of issue when trying to load data based on parameters.

@page "/index"
@page "/index/{id:int}"
@inject ILogger<Index> _logger

<a href="/index?queryparam=abc">queryparam=def</a>
<a href="/index/999">/999</a>

@code {
    [Parameter] public int Id { get; set; }
    [Parameter, SupplyParameterFromQuery(Name = "queryparam")] public string? QueryParamProperty { get; set; }

    public override async Task SetParametersAsync(ParameterView parameters)
    {
        await base.SetParametersAsync(parameters);
        _logger.LogInformation($"SetParametersAsync Id:{Id}, QueryParam:{QueryParamProperty}");
    }
}

This only happens under specific circumstances:

  1. App must have authorization enabled
  2. there is OnNavigateAsync handler on the Router
  3. there is CascadingAuthenticationState on top of the Router (default in blazor template)
@inject IConfiguration Config
<CascadingAuthenticationState>
<Router AppAssembly="@typeof(Program).Assembly" OnNavigateAsync="OnNavigateAsyncHandler">
    <Found Context="routeData">
        <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
        </AuthorizeRouteView>
        <FocusOnNavigate RouteData="@routeData" Selector="[data-action=search]" />
    </Found>
    <NotFound>
    </NotFound>

</Router>
</CascadingAuthenticationState>
@code {
    [Inject] NavigationManager NavigationManager { get; set; } = default!;
    [Inject] AuthenticationStateProvider AuthenticationStateProvider { get; set; } = default!;
    [Inject] ILogger<App> Logger { get; set; } = default!;

    
    protected override async Task OnInitializedAsync()
    {
        ClaimsPrincipal user = (await AuthenticationStateProvider.GetAuthenticationStateAsync()).User;
        await Task.Delay(100);

        await base.OnInitializedAsync();
    }

    void OnNavigateAsyncHandler(NavigationContext context)
    {
        Logger.LogInformation("OnNavigateAsync to '{Path}'", context.Path);
    }
}

Expected Behavior

SetParametersAsync should be called only once per single navigation event

Steps To Reproduce

  1. Download reproducible demo: https://1drv.ms/u/s!An7wnk66a6RRlrI7ETRR9LsXHi2cmg?e=FsLOC2
  2. Start using Visual Studio
  3. Register new user (it uses lndividualAccounts authorization)
  4. Login
  5. Navigate to /index?queryparam=abc
  6. Click the /999 link
  7. Check the console/debug logs

Exceptions (if any)

No response

.NET Version

6.0.400

Anything else?

.NET SDK (reflecting any global.json): Version: 6.0.400 Commit: 7771abd614

Runtime Environment: OS Name: Windows OS Version: 10.0.22000 OS Platform: Windows RID: win10-x64 Base Path: C:\Program Files\dotnet\sdk\6.0.400\

global.json file: Not found

Host: Version: 6.0.8 Architecture: x64 Commit: 55fb7ef977

About this issue

  • Original URL
  • State: open
  • Created 4 years ago
  • Reactions: 16
  • Comments: 23 (2 by maintainers)

Most upvoted comments

Great guys, instead of fixing infra problems you’re focusing on AI bullshit.

Following on from the above, it would be great to get some clarity from the team around whether this is intentional or not. Trouble occurs when we make an HTTP request from within the OnParametersSetAsync() method using the query string parameter - for example, for pagination purposes.

The request fired on the first render returns the result set for page 1, and the request fired for the second render returns the result set for the expected page. If the continuation for the first request is executed after the continuation for the second request, then the incorrect data is displayed to the user.

Query parameters are often optional, so null is usually considered a valid value and an HTTP request to our backend should still be made in this case. I cannot see an obvious (or rather, not unacceptable) way to either avoid the duplicate request being made or to sensibly select which result set we want to prioritise and display in the case that a race occurs.

Having the same problem as @Liero, @danm-de or @axylophon E.g. when having query parameters, which are set via SupplyParameterFromQuery attribute the OnParametersSetAsync is called when navigating away to another page.

Is there any info about investigation or planning of a fix?

I can repro this as well. For now, I’m back to using NavigationManager.LocationChanged + manual query string processing.

.

I’ve come across this in a personal project recently when fiddling around with Blazor Wasm, and it’s stumped me a bit. I’m not hugely familiar with the ASP.NET Core Razor component lifecycle, so this could very well be an intended functionality and this is just me making assumptions!

I’ve got a minimal repro pushed up in a repository on my GitHub here 👉 https://github.com/CharlieJKendall/supply-parameter-from-query-bug

Summary of the repro

Navigating from a page that has a parameter decorated with [SupplyParameterFromQuery] to another page that also has a parameter decorated with [SupplyParameterFromQuery] causes the OnParametersSet() event to fire twice for the page that you are navigating to - the first time with the parameter value is null, and the second time with the parameter populated with the expected value.

Verbose client log output shows that there are in fact two distinct renders happening for the BlazorApp.Pages.Page component which explains why we’re seeing a second call to OnParametersSet(), however I haven’t managed to get to the bottom of why this is happening and why the parameter value has not been bound at this point…

There are then two types of issues:

  1. You describe that the Parameter for the target page is first null and then has the correct value.

  2. The other problem is, that when navigating away the OnParametersSet of the source page is called again.

Good evening everyone,

Im working with Blazor since 2021 (.Net 6) and had this issue (if it even is one) all the time. For that I just want to provide a solution im using in all projects lately. BaseClass.cs

So what it is it catches the SetParametersAsync in a base class and when initiated all necessary parameters it runs a seperate “OnLoaded” and “OnLoadedAsync” method to prevent multiple calls.

For parameters just add them to the list via the “AddParameterToCheck” method.

I’ll do this mostly within the OnInitialized method with a call like:

AddParameterToCheck(nameof(ProductId))

Cheers Florian Zevedei

You can try the following solution for: the Parameter for the target page is first null and then has the correct value.

[SupplyParameterFromQuery]
public string ListType { get; set; }

protected override async Task OnParametersSetAsync()
{
    if (string.IsNullOrWhiteSpace(ListType))
    {
        string[] uriParts = NavigationManager.Uri.Split("?");
        string queryString = uriParts.Length > 1 ? uriParts[1] : string.Empty;
        string queryListType = HttpUtility.ParseQueryString(queryString).Get(nameof(ListType));

        if (!string.IsNullOrWhiteSpace(queryListType)) return;
    }

You can try the following solution for: The first time with the previous value Page=2, the second time with actual value Page=3

[SupplyParameterFromQuery]
public string ListType { get; set; }

protected override async Task OnParametersSetAsync()
{
    string[] uriParts = NavigationManager.Uri.Split("?");
    string queryString = uriParts.Length > 1 ? uriParts[1] : string.Empty;
    string queryListType = HttpUtility.ParseQueryString(queryString).Get(nameof(ListType));

    if (!string.Equals(ListType, queryListType, StringComparison.OrdinalIgnoreCase))
    {
        return;
    }

I’ve come across this in a personal project recently when fiddling around with Blazor Wasm, and it’s stumped me a bit. I’m not hugely familiar with the ASP.NET Core Razor component lifecycle, so this could very well be an intended functionality and this is just me making assumptions!

I’ve got a minimal repro pushed up in a repository on my GitHub here 👉 https://github.com/CharlieJKendall/supply-parameter-from-query-bug

Summary of the repro

Navigating from a page that has a parameter decorated with [SupplyParameterFromQuery] to another page that also has a parameter decorated with [SupplyParameterFromQuery] causes the OnParametersSet() event to fire twice for the page that you are navigating to - the first time with the parameter value is null, and the second time with the parameter populated with the expected value.

Verbose client log output shows that there are in fact two distinct renders happening for the BlazorApp.Pages.Page component which explains why we’re seeing a second call to OnParametersSet(), however I haven’t managed to get to the bottom of why this is happening and why the parameter value has not been bound at this point…

invoke-js.ts:176 dbug: Microsoft.AspNetCore.Components.RenderTree.Renderer[3]
      Rendering component 11 of type Microsoft.AspNetCore.Components.Sections.SectionOutlet+SectionOutletContentRenderer
invoke-js.ts:176 dbug: Microsoft.AspNetCore.Routing.Tree.TreeRouter[1]
      Request successfully matched the route with name '(null)' and template '/page'
invoke-js.ts:176 dbug: Microsoft.AspNetCore.Components.Routing.Router[2]
      Navigating to component BlazorApp.Pages.Page in response to path '/page' with base URI 'https://localhost:7129/'
invoke-js.ts:176 dbug: Microsoft.AspNetCore.Components.RenderTree.Renderer[3]
      Rendering component 1 of type Microsoft.AspNetCore.Components.Routing.Router
invoke-js.ts:176 dbug: Microsoft.AspNetCore.Components.RenderTree.Renderer[3]
      Rendering component 2 of type Microsoft.AspNetCore.Components.RouteView
invoke-js.ts:176 dbug: Microsoft.AspNetCore.Components.RenderTree.Renderer[3]
      Rendering component 3 of type Microsoft.AspNetCore.Components.Routing.FocusOnNavigate
invoke-js.ts:176 dbug: Microsoft.AspNetCore.Components.RenderTree.Renderer[3]
      Rendering component 4 of type Microsoft.AspNetCore.Components.LayoutView
invoke-js.ts:176 dbug: Microsoft.AspNetCore.Components.RenderTree.Renderer[3]
      Rendering component 5 of type BlazorApp.Layout.MainLayout
invoke-js.ts:176 dbug: Microsoft.AspNetCore.Components.RenderTree.Renderer[1]
      Initializing component 14 (BlazorApp.Pages.Page) as child of 5 (BlazorApp.Layout.MainLayout)
invoke-js.ts:176 dbug: Microsoft.AspNetCore.Components.RenderTree.Renderer[4]
      Disposing component 6 of type BlazorApp.Pages.Home
invoke-js.ts:176 dbug: Microsoft.AspNetCore.Components.RenderTree.Renderer[3]
      Rendering component 14 of type BlazorApp.Pages.Page
invoke-js.ts:176 dbug: Microsoft.AspNetCore.Components.RenderTree.Renderer[3]
      Rendering component 14 of type BlazorApp.Pages.Page