Getting a Configuration Value in ASP.NET 5 (vNext) and MVC 6

As you might already know that things has been bit changed for reading appSettings in MVC 6 and Asp.Net 5.

We will go step by step how to achieve this.

First of all as we were used to add Application settings in Web.config till now. But now onwards we need to add these key value in file called config.json as below:


{
"AppSettings": {
    "MyKey" : "MyValue",
    "MyKey2" : "MyValue2"
}
}

 

After this we will create a class which will be used to deserialize those all configurations we provided above.

public class AppSettings
{
    public string MyKey { get; set; }
    public string MyKey2 { get; set; }
}

After this we need to make some change in Startup.cs file as below:


public class Startup
{
    // Set up application services
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseMvc(routes =>
        {
             routes.DefaultHandler = new LocalizedRoute(routes.DefaultHandler);
             routes.MapRoute("default", "{controller}/{action}");
        });

        app.Configure(Configuration.GetSection("AppSettings"));
    }
}

 

Thats it!! Now you are able to use those application setting by simply injecting IOptions<AppSettings> in your controller as below:

public HomeController(IOptions<AppSettings> myAppSettings)
{
    var myKey = myAppSettings.Value.MyKey;
    var myKey2 = myAppSettings.Value.MyKey2;
}

Here IOptions<> interface is part of something called Options Model which is used for accessing POCO style settings(ex: your AppSettings) across your application.

Stay tuned for more updates!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s