1
votes

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?

2
Here's a similar question with a working example: stackoverflow.com/a/32044957/390421 (Which includes loading json data and accessing it through a config.Get() call.)MartijnK
Additionally, you can find more examples on how to access nested json properties here: whereslou.com/2014/05/23/…MartijnK

2 Answers

2
votes

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.

2
votes

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.