Blazor、HttpClient & Config.json
Blazor, HttpClient & Config.json
我刚开始使用 Blazor(Web Assembly)并将其链接到 API。
所以这真的是一个 design/code 问题。
我想配置测试和生产 URL(连接到 API),
不确定我是否正在做这个 right/best 练习,所以任何例子都很好?
(而且我很确定我做错了!)
我想我会在 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"
}
}
在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
将加载相关的 url。
我刚开始使用 Blazor(Web Assembly)并将其链接到 API。 所以这真的是一个 design/code 问题。
我想配置测试和生产 URL(连接到 API), 不确定我是否正在做这个 right/best 练习,所以任何例子都很好? (而且我很确定我做错了!)
我想我会在 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"
}
}
在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
将加载相关的 url。