首页 > 解决方案 > Blazor、HttpClient 和 Config.json

问题描述

我刚刚开始使用 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??";
                }
        }
    } 

应用程序.JSON 文件

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

标签: jsonblazorwebassembly

解决方案


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

appsettings.json

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

appsettings.Development.json

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

Program.cs

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

根据ASPNETCORE_ENVIRONMENT相关的 url 将被加载。


推荐阅读