如何访问 blazor webassembly 中的 appsettings

How to acess the appsettings in blazor webassembly

我目前正在尝试将 api url 保存到应用程序设置中。 但是,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):

appsettings.json:

{
    "api": "https://www.webapiurl.com/"
    "ForceHTTPS": false
}

然后,输入配置 class

 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());
            }
        }
    }

This answer concerned blazor preview when blazor didn't support appsettings.json in wwwroot folder yet. You should use appsettings.json in wwroot folder now and WebAssemblyHostBuilder.Configuration. It also support per environment files (appsettings.{env}.Json).

我通过在应用程序 settings.json 文件夹中使用 settings.json 文件存储并注册一个任务来解决这个问题设置:

Settings.cs

public class Settings
{
    public string ApiUrl { get; set; }
}

wwwroot/settings.json

{
   "ApiUrl": "https://localhost:51443/api"
}

Progam.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);
    }
}

这样做的好处是:

  • 不共享服务器的 appsettings.json 文件,这可能是一个安全漏洞
  • 可根据环境配置

截至目前,您可以使用 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
        }

    }

Inkkiller 成功了。您可以在没有 APIHelper class 的情况下简化对 IConfiguration 的调用,并直接在 Program.cs 中从 WebAssemblyHostBuilder 访问它。

应用程序设置:

{
   "ServerlessBaseURI": "http://localhost:0000/",
}

Program.cs:

public static async Task Main(string[] args)
{
    var builder = WebAssemblyHostBuilder.CreateDefault(args);

    string serverlessBaseURI = builder.Configuration["ServerlessBaseURI"];
}


创建设置 class:

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;
    }
}

您也可以(appsettings.json 在 wwwroot 中):

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) });
    }
}

Blazor WASM appsettings.json

如果 wwwroot 文件夹中没有 appsettings.json,那么只需:

  1. 右键单击 wwwroot 文件夹。
  2. 点击添加 ==> 新项目 ==> 应用程序设置文件

这会将 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()

使用 ASP.NET Core 6.0 Blazor 配置。默认情况下,Blazor WebAssembly 从以下应用设置文件加载配置:

  • wwwroot/appsettings.json.
  • wwwroot/appsettings.{ENVIRONMENT}.json,其中{ENVIRONMENT} 占位符是应用程序的 runtime environment.

示例:

wwwroot/appsettings.json

{
  "h1FontSize": "50px"
}

Pages/ConfigurationExample.剃刀

@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. Don't store app secrets, credentials, or any other sensitive data in the configuration or files of a Blazor WebAssembly app.

https://docs.microsoft.com/en-us/aspnet/core/blazor/fundamentals/configuration?view=aspnetcore-6.0

您还可以将值绑定到 class。

public class ClientAppSettings
{
    public string h1FontSize{ get; set; }
}

然后将这个class作为单例添加到Program.cs中:

var settings = new ClientAppSettings();
builder.Configuration.Bind(settings);
builder.Services.AddSingleton(settings);

将命名空间添加到 _Imports.razor,然后在需要的地方注入以在 Visual Studio 中使用自动完成获取设置:

@inject ClientAppSettings ClientAppSettings

此外,在 .Net 5 和 6 中,您可以将值设置为静态 Class。

示例:

wwwroot/appsettings.json

 "ServicesUrlOptions": {
   "Url": "https://domain.gr/services" }

静态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; }
}

最后绑定值在Program.cs

 builder.Configuration.GetSection(ApplicationServicesSettings.ServicesUrl).Bind(ApplicationServicesSettings.ServicesUrlOptions);

在项目中之后,您可以通过

访问密钥
ApplicationServicesSettings.ServicesUrlOptions.Url