xam developer xam developer - 1 year ago 69
ASP.NET (C#) Question

ASP.NET 5 (vNext) - Getting a Configuration Setting

I'm writing a basic app to learn ASP.NET 5. One area I find very confusing is configuration. Prior to ASP.NET 5, I could do the following:

var settingValue = ConfigurationManager.AppSettings["SomeKey"];

I would have lines of code like that sprinkled throughout my code. Now, in the vNext world, I have a config.json file that looks like this:


"AppSettings": {

Then in Startup.cs, I have the following:

public IConfiguration Configuration { get; set; }
public Startup(IHostingEnvironment environment)
Configuration = new Configuration()

From there, I'm totally stumped. I have MyClass.cs in /src/Website/Code/Models/MyClass.cs.


public class MyClass
public string DoSomething()
var result = string.Empty;
var keyValue = string.Empty; // TODO: What do I do here? How do I get the value of "AppSettings:SomeKey"?
return result;

How do I get the value of "AppSettings:SomeKey"?

Answer Source

I highly recommend using the OptionsModel instead of reading the configuration directly. It allows strong typed model binding to configuration.

Here is an example: GitHub.com/aspnet/Options/test/Microsoft.Extensions.Options.Test/OptionsTest.cs

For your particular case create a model:

class AppSettings {
    public string SomeSetting {get;set;}

and then bind it to your configuration:

var config = // The configuration object
var options = ConfigurationBinder.Bind<AppSettings>(config); 

That way you don't have to worry from where the setting comes from, how it is stored or what is the structure. You simply predefine your options model and magic happens.