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:
- With QueryParam=null
- 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:
- App must have authorization enabled
- there is
OnNavigateAsynchandler on the Router - there is
CascadingAuthenticationStateon 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
- Download reproducible demo: https://1drv.ms/u/s!An7wnk66a6RRlrI7ETRR9LsXHi2cmg?e=FsLOC2
- Start using Visual Studio
- Register new user (it uses lndividualAccounts authorization)
- Login
- Navigate to
/index?queryparam=abc - Click the
/999link - 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)
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
nullis 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
SupplyParameterFromQueryattribute theOnParametersSetAsyncis 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.
.
There are then two types of issues:
You describe that the Parameter for the target page is first null and then has the correct value.
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.
You can try the following solution for: The first time with the previous value Page=2, the second time with actual value Page=3
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 theOnParametersSet()event to fire twice for the page that you are navigating to - the first time with the parameter value isnull, 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.Pagecomponent which explains why we’re seeing a second call toOnParametersSet(), 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…