You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 8 Razor Page同时使用Parameter与SupplyParameterFromQuery参数为空问题

.NET 8 Blazor组件路由参数与查询参数绑定冲突问题

问题场景

配置了两个路由:

  • https://localhost:7215/DemoForm/30030443-2b0c-4b94-959d-fb6132dc164f(路由参数模式)
  • https://localhost:7215/DemoInfo?oid=30030443-2b0c-4b94-959d-fb6132dc164f(查询参数模式)

初始代码

@page "/DemoForm/{rowguid:guid}"
@page "/DemoInfo"

@rendermode InteractiveServer

<h3>Demo</h3>
<h1>Rowguid is @Rowguid</h1>

@code {
    [Parameter, SupplyParameterFromQuery(Name = "oid")]
    public Guid Rowguid { get; set; }
}

预期与实际结果

  • 预期:两个路由均显示 Rowguid is 30030443-2b0c-4b94-959d-fb6132dc164f
  • 实际:
    • 路由1返回 Rowguid is 00000000-0000-0000-0000-000000000000
    • 路由2返回预期结果

修改后正常工作的代码

@page "/DemoForm/{rowguid:guid}"
@page "/DemoInfo"

@rendermode InteractiveServer

<h3>Demo</h3>
<h1>Rowguid is @Rowguid</h1>
<h1>_oid is @_oid</h1>

@code {
    [Parameter]
    public Guid Rowguid { get; set; }

    [SupplyParameterFromQuery(Name = "oid")]
    public Guid? _oid { get; set; }

    protected override Task OnInitializedAsync()
    {
        Rowguid = _oid ?? Rowguid;

        return base.OnInitializedAsync();
    }
}

原因分析

核心问题在于Blazor不支持给同一个属性同时绑定路由参数和查询参数,当你给Rowguid同时标记[Parameter]和[SupplyParameterFromQuery]时,框架的参数绑定逻辑会优先处理查询参数规则:

  1. 访问路由1时,虽然URL里有路由参数rowguid,但框架会尝试从查询参数oid取值,而该路由没有oid参数,因此Rowguid被设为Guid类型的默认值(空Guid)。
  2. 访问路由2时,URL里存在查询参数oid,框架能正确取值,所以显示正常。

修改后的代码把两种绑定逻辑拆分到不同属性:

  • Rowguid仅负责路由参数绑定,对应/DemoForm/{rowguid:guid}的路由参数
  • _oid仅负责查询参数绑定,对应oid查询参数
  • 在OnInitializedAsync生命周期方法中合并取值:如果存在查询参数oid则用它,否则用路由参数的值,这样两种路由场景都能正确获取目标Guid。

内容的提问来源于stack exchange,提问作者HTK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 05:03:18