1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【.NET8】BlazorWebAssemblyでappsettingsから値を取り出す

Last updated at Posted at 2025-03-10

概要

サーバ側のBlazorのProgram.csでappsettings.jsonから設定を取り出す場合、プロジェクト直下にappsettings.jsonを置いてProgram.csでbuilder.Configurationにアクセスすることで設定の値を取り出せますが、WebAssemblyの場合は同じ方法で取り出すことができません。
ネット上にはrazorページなどで設定を取り出す方法は書いてありますが、Program.csで取り出す方法が微妙にわかりづらいです。ちゃんと仕組みを知っていれば簡単なことですが、あまり理解していないとなかなか難しいので、備忘録として残しておきます。

手順

appsettings.jsonはClientのwwwrootに配置しておきます。
Program.csで以下のように記述します。

Program.cs
var builder = WebAssemblyHostBuilder.CreateDefault(args);

// DI に登録される HttpClient の前に直接 HttpClient を生成して設定ファイルを読み込む
var httpClient = new HttpClient
{
    BaseAddress = new Uri(builder.HostEnvironment.BaseAddress)
};
using var stream = await httpClient.GetStreamAsync("appsettings.json");

// appsettings.json を builder.Configuration に追加
builder.Configuration.AddJsonStream(stream);

// builder.Configuration から設定を取得
var configuration = builder.Configuration;

await builder.Build().RunAsync();

やり方としては公式がやっている方法を使ってます。
公式: https://learn.microsoft.com/en-us/aspnet/core/blazor/fundamentals/configuration?view=aspnetcore-8.0

wwwrootに置いてあるappsettings.jsonをhttpClientで取得し、それをbuilder.Configuration.AddJsonStreamで追加しておくことで、builder.Configurationから設定を取得することができるようになります。

最後に

そこまで難しいことではないんですが、理解してないと永遠にハマってしまうポイントじゃないかなと思います。詰まってしまっている方の助けになれば幸いです。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?