【问题标题】:Blazor, HttpClient & Config.jsonBlazor、HttpClient 和 Config.json
【发布时间】:2020-10-27 04:19:35
【问题描述】:

我刚开始使用 Blazor(Web 程序集)并将其链接到 API。 所以这确实是一个设计/代码问题。

我想配置一个测试和生产 URL(连接到 API), 不确定我是否正确/最佳实践,所以任何例子都会很棒? (而且我很确定我做错了!)

我想我会在 Blazor 项目中创建一个 JSON 文件,并且只需要一个生产和测试 URL。 我已经在 program.cs 中开始了这个:

public class Program
    {
        private static string ApiConfig { get; set; }

        public static async Task Main(string[] args)
        {
            var builder = WebAssemblyHostBuilder.CreateDefault(args);
            builder.RootComponents.Add<App>("app");

            LoadJsonConfiguration();

            builder.Services.AddHttpClient<INotificationDataService, NotificationDataService>(client =>
                client.BaseAddress = new Uri("ApiConfig"));

            await builder.Build().RunAsync();
        }

        public static void LoadJsonConfiguration()
        {
            var config = JObject.Parse(@"/Config/application.json");
            
            using (StreamReader file = File.OpenText(@"/Config/application.json"))
                using (JsonTextReader reader = new JsonTextReader(file))
                {
                    var a = reader.Read();
                    ApiConfig = "ReadConfig here??";
                }
        }
    } 

application.JSON 文件

{
  "Url": {
    "LocalTest": "https://localhost:44302",
    "Production": "https://Todo"
  } 
}

【问题讨论】:

    标签: json blazor webassembly


    【解决方案1】:

    wwwroot文件夹中创建两个.json文件,注意名称:

    appsettings.json

    {
      "Url": "https://Todo""  
    }
    

    appsettings.Development.json

    {
      "Url": "https://localhost:44302"  
    }
    

    Program.cs

      var url = builder.Configuration.GetSection("Url").Value;
      ...
    

    将根据ASPNETCORE_ENVIRONMENT 加载相关的网址。

    【讨论】:

      猜你喜欢
      • 2020-10-22
      • 1970-01-01
      • 1970-01-01
      • 2022-08-02
      • 2021-04-21
      • 2019-10-09
      • 2019-10-05
      • 1970-01-01
      • 2019-08-29
      相关资源
      最近更新 更多