【发布时间】:2016-02-23 09:48:39
【问题描述】:
在我的 Startup.cs 文件中,我有以下内容:
public Startup(IHostingEnvironment env)
{
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; set; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
var fooValue = Configuration.Get("foo");
// Add framework services.
services.AddMvc();
}
在我的 appsettings.json 文件中,我有 { "foo": "bar" }
稍后在我的 Startup 课程中,我有:
public void ConfigureServices(IServiceCollection services)
{
var fooValue = Configuration.Get("foo");
// Add framework services.
services.AddMvc();
}
我尝试通过在其上设置断点(带有 ASP.NET 5 扩展的 VS2015)来观察 Locals 调试器中 fooValue 的值变化,但是当我跳过它时出现以下错误:
Microsoft.Extensions.Configuration.Binder.dll 中出现“System.InvalidOperationException”类型的异常,但未在用户代码中处理
附加信息:无法创建“System.String”类型的实例,因为它缺少公共无参数构造函数。
我正在关注MVA Configuring Data at 18m 53s
我已经尝试像示例中那样创建一个 config.json 文件,但模板似乎已更改,并且无论如何都没有帮助。
应该允许我像这样从 .json 文件中获取配置信息吗?
【问题讨论】:
-
这是一个类似的问题和一个工作示例:stackoverflow.com/a/32044957/390421(其中包括加载 json 数据并通过 config.Get() 调用访问它。)
-
此外,您可以在此处找到更多关于如何访问嵌套 json 属性的示例:whereslou.com/2014/05/23/…
标签: c# asp.net-mvc asp.net-core