在 @Ogglas 的回答基础上进行扩展。我将服务的 Configuration.Bind 更改为绑定 appSettings.json 文件中的一个部分。
appSettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"myappSettings": {
"Company": "ACME Sandbox",
"ApiEndpoint": "https://api.sample.com:50443/",
"ImageLocation": "\\\\OnPremise.sample.local\\Images",
"ImageUrl": "https://cdn.somesite.com",
"Emails": {
"RequestTo": "team@degensrt.com",
"SubmittedTo": "team@degensrt.com",
}
}
}
myappSettings.cs
public class myappSettings
{
public string Company { get; set; }
public string ApiEndpoint { get; set; }
public string ImageLocation { get; set; }
public string ImageUrl { get; set; }
public appEmails Emails { get; set; }
}
public class appEmails
{
public string RequestTo { get; set; }
public string SubmittedTo { get; set; }
}
然后在Program.cs中注册并绑定到myappSettings部分。
//Application Settings
var settings = new myappSettings()
builder.Configuration.Bind("myappSettings", settings)
builder.Services.AddSingleton(settings)
然后在您的组件中进行注入和使用:
@inject appSettings appSettings;
....
....
@code {
private string EmailTo = "";
protected override async Task OnInitializedAsync()
{
EmailTo = appSettings.Emails.SubmittedTo;
}
}