Reputation: 3672
In my Startup.cs file I have the following:
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();
}
And in my appsettings.json file I have { "foo": "bar" }
Later in my Startup class I have:
public void ConfigureServices(IServiceCollection services)
{
var fooValue = Configuration.Get("foo");
// Add framework services.
services.AddMvc();
}
I try to watch to value of fooValue change in my Locals debugger by setting a breakpoint on it (VS2015 with the ASP.NET 5 extensions) but I get the following error when I step over it:
An exception of type 'System.InvalidOperationException' occurred in Microsoft.Extensions.Configuration.Binder.dll but was not handled in user code
Additional information: Cannot create instance of type 'System.String' because it is missing a public parameterless constructor.
I'm following the MVA Configuring Data at 18m 53s
I've tried creating a config.json file as in the example, but the template seems to have changed, and it doesn't help anyway.
Should I be allowed to grab configuration info out of .json files like this?
Upvotes: 1
Views: 4508
Reputation: 1530
To answer to your question: yes you can grab the configuration out of .json files, just change
Configuration.Get("foo");
to:
Configuration.Get<string>("foo");
and you will be able to read it.
Upvotes: 2
Reputation: 805
Just to have a full answer here. You were doing everything right, but the overload of CongigurationBinder.Get you chose expects configuration section name instead of a key.
public static T Get<T>(this IConfiguration configuration, T defaultValue)
But there is a different overload you can use:
public static T Get<T>(this IConfiguration configuration, string key)
So your code should look like:
public void ConfigureServices(IServiceCollection services)
{
var fooValue = Configuration.Get<string>("foo");
// Add framework services.
services.AddMvc();
}
I think the documentation is not so clear yet, so I mostly using reflector or GitHub source code to find out what the API is actually doing. Here is a link to the public repository for that package.
Upvotes: 3