如何解决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??";
}
}
}
application.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
,将加载相关的网址。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。