[英]Blazor Webassembly Configuration (appsettings.json) Loading null values in Component Initially
Blazor WebAssembly App Loads Configuration Values After Executing Methods Resulting in Null's Initialy then it will return with correct values. Blazor WebAssembly 应用程序在执行导致 Null 初始化的方法后加载配置值,然后它将返回正确的值。
I followed Microsoft documentation .我遵循了 Microsoft 文档。
Appseting File:应用程序文件:
wwwroot/appsettings.json
My Component.razor:我的组件.razor:
@page "/"
<h1>Configuration example</h1>
<p>Message: @Configuration["message"]</p>
@code {
protected override async Task OnParametersSetAsync()
{
await trying to read Configuration["Message"];
}
}
My Program.cs File:我的 Program.cs 文件:
public class Program
{
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("app");
builder.Services.AddTransient(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
await builder.Build().RunAsync();
}
}
My _Imports.razor我的 _Imports.razor
@using System.Net.Http
@using System.Net.Http.Json
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using Microsoft.AspNetCore.Components.WebAssembly.Http
@using Microsoft.Extensions.Configuration
@using Microsoft.JSInterop
@inject IConfiguration Configuration;
Note: Understand that I am getting the value's correctly but always null first then re-renders with correct values, i am using OnParametersSetAsync() as entry point, i understand OnParametersSetAsync() changes on every Parameter Change.注意:了解我得到的值是正确的,但总是先 null 然后用正确的值重新渲染,我使用 OnParametersSetAsync() 作为入口点,我理解 OnParametersSetAsync() 每次参数更改都会发生更改。 but the Configuration Values should be constant not null first right?但配置值应该是不变的,而不是 null 首先对吧?
I had the same problem today when I tried to fetch connection string value from appsettings.json.今天我尝试从 appsettings.json 获取连接字符串值时遇到了同样的问题。 Try to Restart Visual Studio and it will work properly.尝试重新启动 Visual Studio ,它将正常工作。
The component is instantiated twice, before and after loading data.该组件在加载数据之前和之后实例化了两次。 This is per design to show the page faster and then load the data after.这是为了更快地显示页面然后加载数据的设计。
Why does Blazor renders component twice 为什么 Blazor 渲染组件两次
Why are Blazor lifecycle methods getting executed twice? 为什么 Blazor 生命周期方法会执行两次?
Loading data on component load 加载组件负载数据
https://docs.microsoft.com/en-us/aspnet/core/blazor/components/lifecycle?view=aspnetcore-3.1#stateful-reconnection-after-prerendering https://docs.microsoft.com/en-us/aspnet/core/blazor/components/lifecycle?view=aspnetcore-3.1#stateful-reconnection-after-prerendering
it worked after updating to blazor nuget packages from 3.2.0 to 3.2.1从 3.2.0 到 3.2.1 更新到 blazor nuget 包后它工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.