c# - 静态类中的 Asp.Net Core 配置
问题描述
我想从静态类中的 appsettings.json 文件中读取 url。我尝试了类似的东西
private static string Url => ConfigurationManager.GetSection("Urls/SampleUrl").ToString();
但是每当我尝试调用GetSection()
方法时,我都会得到空值。
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"ConnectionStrings": {
"cs1": "some string",
"cs2": "other string"
},
"Urls": {
"SampleUrl": "google.com"
},
"AllowedHosts": "*"
我只是想从 appsettings 中读取一些数据。根据文档,我不应该以某种方式注册我的标准 appsettings.json 文件,因为Host.CreateDefaultBuilder(args)
在 Program 类中默认情况下会为我执行此操作。
解决方案
正如这里提到的,您可以将静态属性添加到您的Startup.cs
public Startup(IConfiguration configuration)
{
Configuration = configuration;
StaticConfig = configuration;
}
public static IConfiguration StaticConfig { get; private set; }
并在静态类中使用:
var x = Startup.StaticConfig.GetSection("whatever");
推荐阅读
- java - 如何修复线程“main”java.lang.StringIndexOutOfBoundsException中的异常:字符串索引超出范围:错误
- semantic-versioning - 如何在 Mac 上安装 gitversion?
- laravel - json列中的Laravel数据顺序
- debugging - 如何在 IntelliJ 中实时更新调试代码
- node.js - 设置 Access-Control-Allow-Origin 不起作用?
- python - 有没有办法在 Python 中复制任意生成器?
- python - “on_raw_reaction_add”有效而“and on_raw_reaction_remove”无效,为什么?
- python - 基于一列中的条件的 Python for 循环在另一列中返回结果
- xml - 如何使用脚本将 CAML 转换为纯文本?
- typescript - 打字稿:不可分配给类型的参数