不确定我在这里错过了什么,但我无法从我的应用程序设置中获得值。Json在我的。net核心应用程序。我有我的appsettings。json:
{
"AppSettings": {
"Version": "One"
}
}
启动:
public class Startup
{
private IConfigurationRoot _configuration;
public Startup(IHostingEnvironment env)
{
_configuration = new ConfigurationBuilder()
}
public void ConfigureServices(IServiceCollection services)
{
//Here I setup to read appsettings
services.Configure<AppSettings>(_configuration.GetSection("AppSettings"));
}
}
模型:
public class AppSettings
{
public string Version{ get; set; }
}
控制器:
public class HomeController : Controller
{
private readonly AppSettings _mySettings;
public HomeController(IOptions<AppSettings> settings)
{
//This is always null
_mySettings = settings.Value;
}
}
_mySettings总是空的。我是不是遗漏了什么?
我在WPF中遇到了类似的问题。NET Framework 5.0)
我所要做的就是登记。
services.AddSingleton<IConfiguration>(_configuration);
配置本身是这样配置的(在App.xaml.cs中):
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
_configuration = builder.Build();
只需创建一个AnyName.cs文件并粘贴以下代码。
using System;
using System.IO;
using Microsoft.Extensions.Configuration;
namespace Custom
{
static class ConfigurationManager
{
public static IConfiguration AppSetting { get; }
static ConfigurationManager()
{
AppSetting = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("YouAppSettingFile.json")
.Build();
}
}
}
必须替换YouAppSettingFile。Json文件名与您的文件名。
您的.json文件应该如下所示。
{
"GrandParent_Key" : {
"Parent_Key" : {
"Child_Key" : "value1"
}
},
"Parent_Key" : {
"Child_Key" : "value2"
},
"Child_Key" : "value3"
}
现在你可以使用它了。
不要忘记在你想要使用的类中添加引用。
using Custom;
检索值的代码。
string value1 = ConfigurationManager.AppSetting["GrandParent_Key:Parent_Key:Child_Key"];
string value2 = ConfigurationManager.AppSetting["Parent_Key:Child_Key"];
string value3 = ConfigurationManager.AppSetting["Child_Key"];
亚比谢克的回答是:
如果你想将值导入到静态类中,那么只需使用(ReSharper推荐):
static IConfiguration conf = (JsonConfigurationExtensions.AddJsonFile(new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()), "appsettings.json").Build());
private static string AuthorizationServiceURL { get; } = conf["ServiceUrls:AuthorizationUrl"];
// appsettings.json
{
"ServiceUrls": {
"AuthorizationUrl": "https://example.com/authorize"
}
}