【问题标题】:How to acess the appsettings in blazor webassembly如何访问 blazor webassembly 中的 appsettings
【发布时间】:2020-06-18 12:32:05
【问题描述】:

我正在尝试将 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();
}

【问题讨论】:

  • hutchcodes.net/2019/12/blazor-wasm-app-settings "没有简单的方法将设置传递到客户端 Blazor 应用程序,因此我们需要应用程序从服务器请求它们。我们将创建一个 ClientAppSettingsController 到 AppSettingsExample.Server 来提供这些设置。"

标签: c# blazor blazor-client-side


【解决方案1】:

使用 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.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

【讨论】:

    【解决方案2】:

    当 blazor 尚不支持 wwwroot 文件夹中的 appsettings.json 时,此答案涉及 blazor 预览。您现在应该使用 wwroot 文件夹中的 appsettings.json 和 WebAssemblyHostBuilder.Configuration。它还支持每个环境文件(appsettings.{env}.Json)。

    我通过在应用程序 wwwroot 文件夹中使用 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 文件,这可能是一个安全漏洞
    • 可根据环境进行配置

    【讨论】:

    • 非常感谢!昨天我可以理解它。
    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

      你也可以(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) });
          }
      }
      

      【讨论】:

      • 这是问题的准确答案。在 net6 中没有类 Program { ... } 是一样的
      【解决方案5】:

      创建设置类:

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

      【讨论】:

        【解决方案6】:

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

        【讨论】:

          【解决方案7】:

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

          【讨论】:

            【解决方案8】:

            作为一个例子,我有它这样实现(客户端 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());
                        }
                    }
                }
            

            【讨论】:

            • 我的应用没有 startup.cs。一切都通过program.cs。来自火星答案的阿瓜绕过它。
            猜你喜欢
            • 2020-07-14
            • 2020-10-24
            • 1970-01-01
            • 2020-11-22
            • 1970-01-01
            • 1970-01-01
            • 2020-08-19
            • 2020-06-26
            • 1970-01-01
            相关资源
            最近更新 更多