我有一个像这样的 Blazor 页面:
@PAGE
<h1>Hello, world!</h1>
<h2>The time on the server is @DateTime.Now LAT:@Request.Query["lat"] LONG:@Request.Query["long"]</h2>
我也尝试过
<h2>The time on the server is @DateTime.Now LAT:@Context.Request.Query["lat"] LONG:@Context.Request.Query["long"]</h2>
和
<h2>The time on the server is @DateTime.Now LAT:@HttpContext.Current.Request.Query["lat"]
LONG:@HttpContext.Current.Request.Query["long"]</h2>
但是 IDE 不理解
Context
/ 或 HttpContext.Current
尝试注入 NavigationManager 服务以访问查询字符串参数。
@page "/"
@using Microsoft.AspNetCore.Components
@inject NavigationManager Navigation
<h1>Hello, world!</h1>
<h2>The time on the server is @DateTime.Now</h2>
<h2>LAT: @latitude LONG: @longitude</h2>
@code {
private string latitude;
private string longitude;
protected override void OnInitialized()
{
var uri = Navigation.ToAbsoluteUri(Navigation.Uri);
var queryParameters = Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(uri.Query);
if (queryParameters.TryGetValue("lat", out var lat))
{
latitude = lat;
}
if (queryParameters.TryGetValue("long", out var lon))
{
longitude = lon;
}
}
}
要读取 GET 字符串参数,可以使用
[SupplyParameterFromQuery]
属性指定组件参数来自查询字符串。
您可以在此链接找到详细的使用说明:https://learn.microsoft.com/en-us/aspnet/core/blazor/fundamentals/routing?view=aspnetcore-8.0#query-strings
1。以下是可在 Blazor Web 和 Blazor WebAssembly 应用程序上运行的代码:
@page "/Test"
<h3>Test</h3>
<h1>Test Read Query Parameter</h1>
<h2>The time on the server is @DateTime.Now</h2>
<h2>LAT: @Lat LONG: @Long</h2>
@code {
[SupplyParameterFromQuery]
public string? Lat { get; set; }
[SupplyParameterFromQuery]
public string? Long { get; set; }
}
我的测试结果:
2。这是可以在 Blazor 服务器上运行的代码:
@page "/Test/{Lat}/{Long}"
<h3>Test</h3>
<h1>Test Read Query Parameter</h1>
<h2>The time on the server is @DateTime.Now</h2>
<h2>LAT: @Lat LONG: @Long</h2>
@code {
[Parameter]
public string? Lat { get; set; }
[Parameter]
public string? Long { get; set; }
}
或
@page "/Test2"
@inject NavigationManager Navigation
<h3>Test</h3>
<h1>Test Read Query Parameter</h1>
<h2>The time on the server is @DateTime.Now</h2>
<h2>LAT: @Lat LONG: @Long</h2>
@code {
public string? Lat { get; set; }
public string? Long { get; set; }
protected override void OnInitialized()
{
var uri = Navigation.ToAbsoluteUri(Navigation.Uri);
var queryParameters = System.Web.HttpUtility.ParseQueryString(uri.Query);
if (queryParameters.HasKeys())
{
if (queryParameters.AllKeys.Contains("Lat"))
{
Lat = queryParameters["Lat"];
}
if (queryParameters.AllKeys.Contains("Long"))
{
Long = queryParameters["Long"];
}
}
}
}