[英]Blazor WebAssembly - appsettings.json as dependency while registering services
[英]How to acess the appsettings in blazor webassembly
我正在嘗試將 api url 保存在 appsettings 中。 但是, configuration.Propertiers 似乎是空的。 我不確定如何獲得設置。 在 program.cs 中:
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
//string url = builder.Configuration.Properties["APIURL"].ToString();
foreach (var prop in builder.Configuration.Properties)
Console.WriteLine($"{prop.Key} : {prop.Value}" );
//builder.Services.AddSingleton<Service>(new Service(url));
builder.RootComponents.Add<App>("app");
await builder.Build().RunAsync();
}
當 blazor 尚不支持 wwwroot 文件夾中的 appsettings.json 時,此答案涉及 blazor 預覽。 您現在應該在 wwroot 文件夾中使用 appsettings.json 和
WebAssemblyHostBuilder.Configuration
。 它還支持每個環境文件(appsettings.{env}.Json)。
我通過使用應用程序wwwroot文件夾中的settings.json文件存儲解決了這個問題,並注冊了一個任務來獲取設置:
設置.cs
public class Settings
{
public string ApiUrl { get; set; }
}
wwwroot/settings.json
{
"ApiUrl": "https://localhost:51443/api"
}
程序.cs
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.Services.AddSingleton(async p =>
{
var httpClient = p.GetRequiredService<HttpClient>();
return await httpClient.GetJsonAsync<Settings>("settings.json")
.ConfigureAwait(false);
});
SampleComponent.razor
@inject Task<Settings> getsettingsTask
@inject HttpClient client
...
@code {
private async Task CallApi()
{
var settings = await getsettingsTask();
var response = await client.GetJsonAsync<SomeResult>(settings.ApiUrl);
}
}
這有以下優點:
Inkkiller 做到了。 您可以在沒有 APIHelper 類的情況下簡化對 IConfiguration 的調用,並從 WebAssemblyHostBuilder 直接在 Program.cs 中訪問它。
應用設置:
{
"ServerlessBaseURI": "http://localhost:0000/",
}
程序.cs:
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
string serverlessBaseURI = builder.Configuration["ServerlessBaseURI"];
}
您也可以(wwwroot 中的 appsettings.json):
public class Program
{
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("app");
var url = builder.Configuration.GetValue<string>("ApiConfig:Url");
builder.Services.AddTransient(sp => new HttpClient { BaseAddress = new Uri(url) });
}
}
使用 ASP.NET Core 6.0 Blazor 配置。 Blazor WebAssembly 默認從以下應用設置文件加載配置:
例子:
wwwroot/appsettings.json
{
"h1FontSize": "50px"
}
Pages/ConfigurationExample.razor
@page "/configuration-example"
@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration
<h1 style="font-size:@Configuration["h1FontSize"]">
Configuration example
</h1>
警告 Blazor WebAssembly 應用中的配置和設置文件對用戶可見。 不要將應用機密、憑據或任何其他敏感數據存儲在 Blazor WebAssembly 應用的配置或文件中。
https://docs.microsoft.com/en-us/aspnet/core/blazor/fundamentals/configuration?view=aspnetcore-6.0
您還可以將值綁定到一個類。
public class ClientAppSettings
{
public string h1FontSize{ get; set; }
}
然后將此類添加為 Program.cs 中的 Singleton:
var settings = new ClientAppSettings();
builder.Configuration.Bind(settings);
builder.Services.AddSingleton(settings);
將命名空間添加到_Imports.razor
,然后在需要的地方注入以在 Visual Studio 中使用自動完成功能獲取設置:
@inject ClientAppSettings ClientAppSettings
到目前為止,您可以使用IConfiguration
。
appsettings.json:
{
"Services": {
"apiURL": "https://localhost:11111/"
}
}
.
using Microsoft.Extensions.Configuration;
public class APIHelper
{
private string apiURL;
public APIHelper(IConfiguration config)
{
apiURL = config.GetSection("Services")["apiURL"];
//Other Stuff
}
}
Blazor WASM appsettings.json
如果wwwroot
文件夾中沒有appsettings.json
,那么只需:
wwwroot
文件夾。這會將appsettings.json
添加到您的應用程序中。 打開appsettings.json
文件,您將在其中看到一個部分,用於數據庫添加一個部分,就像我添加了apiinfo
:
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=_CHANGE_ME;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"apiinfo":{
"apiurl": "your api url"
}
}
現在,當您想調用此部分時,只需注入配置並將其稱為:
@inject Microsoft.Extensions.Configuration.IConfiguration config;
並調用apiurl
:
config.GetSection("apiinfo")["apiurl"].ToString()
作為一個例子,我有它像這樣實現(客戶端 Blazor):
appsettings.json:
{
"api": "https://www.webapiurl.com/"
"ForceHTTPS": false
}
然后,輸入了配置類
public class APISetting
{
public string api { get; set; }
public bool ForceHTTPS { get; set; }
}
然后,在啟動時加載:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton(GetConfiguration());
}
public void Configure(IComponentsApplicationBuilder app )
{
app.AddComponent<App>("app");
}
public APISetting GetConfiguration()
{
using (var stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("appsettings.json"))
using (var reader = new System.IO.StreamReader(stream))
{
return System.Text.Json.JsonSerializer.Deserialize<APISetting>(reader.ReadToEnd());
}
}
}
同樣在 .Net 5 & 6 中,您可以將值設置為靜態類。
例子:
wwwroot/appsettings.json
"ServicesUrlOptions": {
"Url": "https://domain.gr/services" }
靜態類
public static class ApplicationServicesSettings
{
public const string ServicesUrl = "ServicesUrlOptions";
public static ServicesUrlOptions ServicesUrlOptions { get; set; } = new ServicesUrlOptions();
}
public class ServicesUrlOptions
{
public string Url { get; set; }
}
最后綁定 Program.cs 的值
builder.Configuration.GetSection(ApplicationServicesSettings.ServicesUrl).Bind(ApplicationServicesSettings.ServicesUrlOptions);
在項目中之后,您可以通過以下方式訪問密鑰
ApplicationServicesSettings.ServicesUrlOptions.Url
創建設置類:
public class Settings
{
public string ApiUrl { get; set; }
}
在 wwwroot 文件夾中創建 settings.json:
{
"ApiUrl": "http://myapiurlhere"
}
並在 .razor 組件中像這樣讀取它:
@inject HttpClient Http
...
@code {
private string WebApuUrl = "";
protected override async Task OnInitializedAsync()
{
var response = await Http.GetFromJsonAsync<Settings>("settings.json");
WebApuUrl = response.ApiUrl;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.