ドキュメントを軽くあさってみたら Blazor WebAssembly で、既に構成ファイルの扱いまでサポートしているんですね。
ASP.NET Core Blazor hosting model configuration
ということで試してみました。
Blazor WebAssembly のプロジェクトを作成しておきます。
NuGet のパッケージの管理で Blazor まわりのライブラリが 3.2 の Preview 3 以降であることを確認します。
では、構成ファイルを置いてい置きましょう。Blazor WebAssembly では wwwroot の下に構成ファイルを置くみたいです。こんな感じで。
それぞれの中身はこのようにしてみました。
{
"message": "Hello from appsettings.json"
}
{
"envMessage": "Hello from appsettings.Development.json"
}
{
"envMessage": "Hello from appsettings.Production.json"
}
そして、Program.cs で以下のようにして IConfiguration から適当なクラスにマッピングして DI 出来るように下準備をしてやります。
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Text;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
namespace BlazorApp3
{
public class Program
{
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("app");
builder.Services.AddBaseAddressHttpClient();
// IConfiguration から AppSettings クラスにして DI できるようにしておく
builder.Services.AddSingleton(p => p.GetRequiredService<IConfiguration>().Get<AppSettings>());
await builder.Build().RunAsync();
}
}
// appsettings.json の値を入れるよう
public class AppSettings
{
public string Message { get; set; }
public string EnvMessage { get; set; }
}
}
あとは、普通に DI するなりして使いましょう。こんな感じで
@page "/"
@inject AppSettings _appSettings
<h1>Hello, world!</h1>
Welcome to your new app.
<p>@_appSettings.Message</p>
<p>@_appSettings.EnvMessage</p>
因みに、Program.cs で Configure メソッドで DI コンテナに登録して IOptions<T>
で受けるのは出来ませんでした。Configure をするには、IConfiguration のインスタンスが必要で、それをしようとしたら builder.Build().Configuration
で取得しないといけないのですが、builder.Build()
は 2 回やると appsettings.json
とかを読み込むための Stream を 2 回読むことになっているっぽくて、そこで例外が出てるように見えます。(深追いはしていない
Blazor のアプリを実行してみると、ちゃんと思った通りのメッセージが出ます。開発者ツールで見てみると appsettings.json と appsettings.Development.json を、サーバーから取得していることがわかります。
Production の方は、何処かにデプロイされると読み込まれるらしいです。試しに、Azure ストレージアカウントの Blob の静的サイトのホスト機能を使って作ったサイトに置いてみました。発行をして発行先フォルダーの wwwroot フォルダーの下を全部 Blob の $web コンテナーにコピーします。
今度はちゃんと Hello from appsettings.Production.json というメッセージが出てますね。
まとめ
ちゃんと動くね。ということで、ドキュメントにも書かれていますが、このような仕組みなので URL に appsettings.json と打ち込むと生 JSON が手に入っちゃうので、間違っても秘密な情報は書かないように気をつけましょう。