json - 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"
}
}
解决方案
.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 将被加载。
推荐阅读
- c# - Windows 和 Linux 的 Process.Start() 区别
- mysql - 无法在 macOs (Xampp) 上的 MySQL Workbench 上获取表
- c# - 如何从 App.xaml 而不是 App.xaml.cs 设置 MainPage?
- matlab - 函数 cputime 到函数 tic toc 的转换
- php - SQL 查询 - 数组但特定列仅显示 1 次
- postgresql - 在 postgresql 10 中使用逻辑复制时有什么方法可以截断?
- ssl - Hyperlegder Fabric:CA证书没有CA属性,即使它有
- python - 如何检测列表中的每个数字是否等于或小于零?
- sql-server - xml.node 如何获取值
- python - Python 3-编写一个从文件中读取数字的程序,月份名称不会打印,错误