首页 > 解决方案 > Blazor Webassembly 配置 (appsettings.json) 最初在组件中加载空值

问题描述

Blazor WebAssembly 应用程序在执行导致 Null 初始化的方法后加载配置值,然后它将返回正确的值。

我遵循了 Microsoft 文档

应用程序文件:

wwwroot/appsettings.json

我的 Component.razor:

@page "/"

<h1>Configuration example</h1>

<p>Message: @Configuration["message"]</p>
@code {
   protected override async Task OnParametersSetAsync()
   {
      await trying to read Configuration["Message"];
    }
}

我的 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();
    }
}

我的 _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;

注意:了解我得到的值是正确的,但总是首先为空,然后使用正确的值重新渲染,我使用 OnParametersSetAsync() 作为入口点,我理解 OnParametersSetAsync() 每次参数更改都会发生更改。但是配置值首先应该是常量而不是 null 对吗?

标签: c#blazorwebassemblyblazor-webassembly

解决方案



推荐阅读