[英]How to acess the appsettings in blazor webassembly
I currentying trying to save the api url in an appsettings.我正在尝试将 api url 保存在 appsettings 中。 However, the configuration.Propertiers seems to be empty.
但是, configuration.Propertiers 似乎是空的。 I am not sure how to get the setting.
我不确定如何获得设置。 in program.cs:
在 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();
}
This answer concerned blazor preview when blazor didn't support appsettings.json in wwwroot folder yet.
当 blazor 尚不支持 wwwroot 文件夹中的 appsettings.json 时,此答案涉及 blazor 预览。 You should use appsettings.json in wwroot folder now and
WebAssemblyHostBuilder.Configuration
.您现在应该在 wwroot 文件夹中使用 appsettings.json 和
WebAssemblyHostBuilder.Configuration
。 It also support per environment files (appsettings.{env}.Json).它还支持每个环境文件(appsettings.{env}.Json)。
I solve this issue by using a settings.json file store in the app wwwroot folder and register a task to get the settings :我通过使用应用程序wwwroot文件夹中的settings.json文件存储解决了这个问题,并注册了一个任务来获取设置:
Settings.cs设置.cs
public class Settings
{
public string ApiUrl { get; set; }
}
wwwroot/settings.json wwwroot/settings.json
{
"ApiUrl": "https://localhost:51443/api"
}
Progam.cs程序.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 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);
}
}
This has advantages:这有以下优点:
Inkkiller nailed it. Inkkiller 做到了。 You can simplify the call into IConfiguration without the APIHelper class and access it directly in Program.cs from the WebAssemblyHostBuilder.
您可以在没有 APIHelper 类的情况下简化对 IConfiguration 的调用,并从 WebAssemblyHostBuilder 直接在 Program.cs 中访问它。
appsettings:应用设置:
{
"ServerlessBaseURI": "http://localhost:0000/",
}
Program.cs:程序.cs:
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
string serverlessBaseURI = builder.Configuration["ServerlessBaseURI"];
}
You can also just (appsettings.json in wwwroot):您也可以(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) });
}
}
Using ASP.NET Core 6.0 Blazor configuration.使用 ASP.NET Core 6.0 Blazor 配置。 Blazor WebAssembly loads configuration from the following app settings files by default:
Blazor WebAssembly 默认从以下应用设置文件加载配置:
Example:例子:
wwwroot/appsettings.json wwwroot/appsettings.json
{
"h1FontSize": "50px"
}
Pages/ConfigurationExample.razor Pages/ConfigurationExample.razor
@page "/configuration-example"
@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration
<h1 style="font-size:@Configuration["h1FontSize"]">
Configuration example
</h1>
Warning Configuration and settings files in a Blazor WebAssembly app are visible to users.
警告 Blazor WebAssembly 应用中的配置和设置文件对用户可见。 Don't store app secrets, credentials, or any other sensitive data in the configuration or files of a Blazor WebAssembly app.
不要将应用机密、凭据或任何其他敏感数据存储在 Blazor WebAssembly 应用的配置或文件中。
https://docs.microsoft.com/en-us/aspnet/core/blazor/fundamentals/configuration?view=aspnetcore-6.0 https://docs.microsoft.com/en-us/aspnet/core/blazor/fundamentals/configuration?view=aspnetcore-6.0
You can also bind the values to a class.您还可以将值绑定到一个类。
public class ClientAppSettings
{
public string h1FontSize{ get; set; }
}
Then add this class as a Singleton in Program.cs:然后将此类添加为 Program.cs 中的 Singleton:
var settings = new ClientAppSettings();
builder.Configuration.Bind(settings);
builder.Services.AddSingleton(settings);
Add namespace to _Imports.razor
and then inject where needed to get settings with autocomplete in Visual Studio:将命名空间添加到
_Imports.razor
,然后在需要的地方注入以在 Visual Studio 中使用自动完成功能获取设置:
@inject ClientAppSettings ClientAppSettings
As of now, you can use the IConfiguration
.到目前为止,您可以使用
IConfiguration
。
appsettings.json: 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
Blazor WASM
appsettings.json
If you dont have appsettings.json
in the wwwroot
folder then simply:如果
wwwroot
文件夹中没有appsettings.json
,那么只需:
wwwroot
folder.wwwroot
文件夹。This will add appsettings.json
to your application.这会将
appsettings.json
添加到您的应用程序中。 Open the appsettings.json
file you will see a section in it already for database add a section like I have added apiinfo
:打开
appsettings.json
文件,您将在其中看到一个部分,用于数据库添加一个部分,就像我添加了apiinfo
:
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=_CHANGE_ME;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"apiinfo":{
"apiurl": "your api url"
}
}
Now when you want to call this section simply Inject configuration and call it like:现在,当您想调用此部分时,只需注入配置并将其称为:
@inject Microsoft.Extensions.Configuration.IConfiguration config;
And to call the apiurl
:并调用
apiurl
:
config.GetSection("apiinfo")["apiurl"].ToString()
as an example, I have it implemeneted like this (client-side Blazor):作为一个例子,我有它像这样实现(客户端 Blazor):
appsettings.json: appsettings.json:
{
"api": "https://www.webapiurl.com/"
"ForceHTTPS": false
}
then, have typed config class然后,输入了配置类
public class APISetting
{
public string api { get; set; }
public bool ForceHTTPS { get; set; }
}
then, load on startup:然后,在启动时加载:
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());
}
}
}
Also in .Net 5 & 6 you can set the value to Static Class.同样在 .Net 5 & 6 中,您可以将值设置为静态类。
Example:例子:
wwwroot/appsettings.json wwwroot/appsettings.json
"ServicesUrlOptions": {
"Url": "https://domain.gr/services" }
Static Class静态类
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; }
}
Finally bind the value at Program.cs最后绑定 Program.cs 的值
builder.Configuration.GetSection(ApplicationServicesSettings.ServicesUrl).Bind(ApplicationServicesSettings.ServicesUrlOptions);
After in project you have access to key by在项目中之后,您可以通过以下方式访问密钥
ApplicationServicesSettings.ServicesUrlOptions.Url
create settings class:创建设置类:
public class Settings
{
public string ApiUrl { get; set; }
}
create settings.json in wwwroot folder:在 wwwroot 文件夹中创建 settings.json:
{
"ApiUrl": "http://myapiurlhere"
}
and in .razor component read it like this:并在 .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.