Blazor Server如何获取PHP风格?parameter=形式的URL查询参数
解决方案
方案1:使用[SupplyParameterFromQuery]特性(适用于.NET 6及以上版本)
这是官方提供的最便捷的查询参数获取方式,仅需要两步修改即可:
- 修改
Authentication.razor的路由定义,移除路径参数配置:
@page "/authentication" <PageTitle>APP | Authentication</PageTitle> <div>Some html to render the component</div>
- 修改
Authentication.razor.cs的参数属性,给Code参数添加[SupplyParameterFromQuery]特性:
public partial class Authentication { [Parameter] [SupplyParameterFromQuery(Name = "code")] public string? Code { get; set; } protected override async Task OnInitializedAsync() { // 组件初始化完成后Code会自动赋值,可直接调用认证逻辑 if (!string.IsNullOrEmpty(Code)) { await Authenticate(); } } private async Task Authenticate() { // 此处编写用Code换取访问令牌的业务逻辑 } }
特性中的Name = "code"对应查询字符串里的参数名,和URL中?code=xxx的参数名匹配即可,如果属性名和查询参数名完全一致可以省略该配置。
方案2:手动解析查询字符串(兼容所有.NET版本)
如果你使用的是.NET 6之前的版本,可以通过注入NavigationManager手动解析参数:
using Microsoft.AspNetCore.WebUtilities; using Microsoft.AspNetCore.Components; using System; public partial class Authentication { [Inject] private NavigationManager NavManager { get; set; } public string? Code { get; set; } protected override async Task OnInitializedAsync() { // 解析当前URI的查询参数 var uri = new Uri(NavManager.Uri); if (QueryHelpers.ParseQuery(uri.Query).TryGetValue("code", out var codeValue)) { Code = codeValue; if (!string.IsNullOrEmpty(Code)) { await Authenticate(); } } } private async Task Authenticate() { // 此处编写用Code换取访问令牌的业务逻辑 } }
配置完成后即可通过myapplink.com/authentication?code=1234-qwerty-login-code正常获取到参数值。
内容的提问来源于stack exchange,提问作者Zakaria Guenna
相关产品推荐
相关产品推荐

