引用 Microsoft.AspNetCore.App 元包或将包引用添加到 Microsoft.Extensions.Options.ConfigurationExtensions 包。
简而言之,直接可以用:
Appsetting.json
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"Setting": {
"Url": "http://localhost:8080/",
"LogPath": "D/ItemService"
},
"AllowedHosts": "*"
}
configuration["Setting:Url"]
configuration.GetValue<string>("Setting:Url")
configuration GetSection("Setting"). GetSection("Url")
方法二:
新建model类Settings
{
Public string A{get;set;}
};
其中A对应与json中配置文件的key,这里类是
{
Public string Url{get;set;}
Public string LogPath{get;set;}
};
在Startup.cs中ConfigureServices的方法
services.Configure<Settings>(options =>
{
options.ConnectionString = configuration.GetSection("Setting:Url").Value;
options.Database = configuration.GetSection("Setting:LogPath").Value;
});
使用:这样可以在全局拿到配置文件
public BController(IOptions<Settings> settings)
{
url=settings.Value.Url;
logpath = settings.Value.LogPath);
}