ASP.NET 5: Configuration

4.5 (12 votes)

This is the third in a series of articles that explores ASP.NET 5 by reconstructing the Visual Studio 2015 Web Application template from an Empty template. This article looks at the new configuration system added to ASP.NET 5 and will also cover how services like Entity Framework and MVC itself are added to the project. The series of articles has been developed using Visual Studio RTM and ASP.NET 5 Beta 6. It will be kept updated along with newer releases.

Goodbye XML, Hello JSON

In the past, ASP.NET has been built on a foundation of XML. Web Forms .aspx and .ascx files are basically XML files and configuration in previous versions of ASP.NET is managed in an XML file called web.config. The web.config file has a particular structure and a class (System.Web.Configuration.WebConfigurationManager) devoted to providing access to it. In ASP.NET 5 JSON is the preferred format for storing structured information such as configuration. This change has largely been driven, I suspect, by the desire to appeal to web developers working on other platforms who are more used to JSON as a structured data format. The first article in this series has already looked at the new JSON solution and project files: global.json and project.json.

The default replacement for the web.config file is config.json. You can also choose to use an XML file if you prefer, and INI files, environment variables, command line arguments and an in-memory option are supported natively too. The template for a config.json file is labelled as ASP.NET Configuration File in the Add New Item dialog:

MVC 6 and EF 7

 

When you add one, the templated content provides a placeholder for a connection string:

{
    "Data": {
        "DefaultConnection": {
            "ConnectionString": "Server=(localdb)\\MSSQLLocalDB;Database=_CHANGE_ME;Trusted_Connection=True;"
        }
    }
}

Strongly Typed AppSettings

In earlier versions of ASP.NET, it is quite common to store application-wide constants in the appSettings section of a web.config file. You can store these values in the config.json file instead. Previous Beta release templates included an example of this, but it has been removed from the Beta 6 template. The steps described below demonstrate how to use the config.json file to store appsettings and how to provide strongly-typed access to them.

  1. Add the highlighted code to the config.json file:

    {
        "AppSettings" : {
            "SiteTitle" :  "My Web Site"
        },
        "Data": {
            "DefaultConnection": {
                "ConnectionString": "Server=(localdb)\\MSSQLLocalDB;Database=_CHANGE_ME;Trusted_Connection=True;"
            }
        }
    }
  2. Right click on the Properties node in Solution Explorer (depicted by a wrench icon) and select Add ยป New Item.

  3. Add a C# class file named AppSettings.cs and replace its default content with the following:

    namespace WebApplication2
    {
        public class AppSettings
        {
            public string SiteTitle { get; set; }
        }
    }
    
  4. Change the dependencies section in project.json to include the highlighted lines below

      "dependencies": {
        "Microsoft.AspNet.Server.IIS": "1.0.0-beta6",
        "Microsoft.AspNet.Server.WebListener": "1.0.0-beta6",
        "Microsoft.AspNet.Mvc": "6.0.0-beta6",
        "Microsoft.Framework.Configuration.Json": "1.0.0-beta6"
      },
  5. Make the following highlighted changes to Startup.cs:

    using Microsoft.AspNet.Builder;
    using Microsoft.AspNet.Hosting;
    using Microsoft.AspNet.Http;
    using Microsoft.Framework.Configuration;
    using Microsoft.Framework.DependencyInjection;
    using Microsoft.Framework.OptionsModel;
    using Microsoft.Framework.Runtime;
    
    namespace WebApplication2
    {
        public class Startup
        {
            public IConfiguration Configuration { get; set; }
    
            public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
            {
                var builder = new ConfigurationBuilder(appEnv.ApplicationBasePath)
                    .AddJsonFile("config.json");
                Configuration = builder.Build();
            }
            public void ConfigureServices(IServiceCollection services)
            {
                services.Configure<AppSettings>(Configuration.GetConfigurationSection("AppSettings"));
                services.AddMvc();
            }
    
            public void Configure(IApplicationBuilder app)
            {
                var appSettings = app.ApplicationServices.GetService<IOptions<AppSettings>>();
                app.Run(async (context) =>
                {
                    await context.Response.WriteAsync(appSettings.Options.SiteTitle);
                });
            }
        }
    }
    
  6. Press Ctrl+F5 to run the application without debugging. You should see "My Web Site" written to the browser.

    MVC 6 and EF 7

You started by adding a new section called AppSettings to the config.json file and declaring a property with a value. Then you created a C# class called AppSettings with one property that matches the one you added to the config file. The AppSettings class is designed to provide strongly typed access to the appSettings section of the config.json file. You added a couple of packages to the project.json file to make them available to the application. The first package enables you to use JSON as the format for your configuration data. The second package introduces MVC into the application.

In the Startup class, you added a constructor where you instantiated a variable representing the project's configuration as the config.json file and assigned that to a property that you created of type IConfiguration. This holds the values loaded from the configuration source (the config.json file). You made the AppSettings available to the application by registering it with the dependency injection system in the ConfigureServices method. The method you used mapped the json values from the configuration file to the AppSettings class. You also registered the MVC framework with the dependency injection system. Finally, you used the GetService<T> extension method to retrieve the AppSettings from the DI system in the Startup class'sConfigure method where you used them to write the SiteTitle value to the browser.

Summary

The configuration model introduced with ASP.NET 5 is a world away from the one in previous versions of ASP.NET. It is a plug and play system that supports various data formats (JSON, XML, INI files) out of the box. You can also write your own configuration providers to cater for alternative formats. This article looked at the default JSON format and saw how to add new sections. It also covered how to reference the values in the new section in a strongy typed manner through the use of Options. You saw how to make the configuration available as a service which you registered with the built-in Dependency Injection system. In the next article, I will explore dependency injection in ASP.NET 5 in more detail.

You might also like...

Date Posted:
Last Updated:
Posted by:
Total Views to date: 18045

4 Comments

- Tom Donino

ConfigurationBuilder takes an array of IConfigurationProviders, not a string which appEnv.ApplicationBasePath is, was this a change in beta8 which is what I installed? I assume this method will not work in .Net4.6 since you are using MVC6 reference?

- Mike

@Tom,

There could well have been a change since I wrote the article based on Beta 4. I haven't had the time or inclination to catch up since then. I'll review when the whole things ships properly.

Config in 4.6 is the same as 4.5. It's still based on web.config.

- anne

This is the best tutorial that I've found - thank you!

I need to create a Web API and I'm wondering whether vs 2015 is stable enough - any ideas?

- Larry

For RC.1 the services code ends up being:

services.Configure(Configuration.GetSection("AppSettings"));

Recent Comments

dave 20/08/2016 14:57
In response to ASP.NET Web Pages vNext or Razor Pages
Do SimplemembershipProvider in viewpages is supported?...

Steven 18/08/2016 04:40
In response to Entity Framework Code First and Stored Procedures
Can you provide the directives (using statements) you're using for EF7 example?...

yousaid 17/08/2016 22:08
In response to ASP.NET Web Pages vNext or Razor Pages
Increasingly, learning a Microsoft tool is no longer worth the return on investment. Too many tools...

jared 12/08/2016 05:54
In response to ASP.NET Web Pages vNext or Razor Pages
hi mike, just for clarification, is viewpages something different from webpages? is webpages still...

Jocke 08/08/2016 20:37
In response to Loading ASP.NET Core MVC Views From A Database Or Other Location
Good post! If this was to be implemented in a CMS where users can change the view files, how would I...

cyrus 05/08/2016 19:49
In response to ASP.NET Web Pages vNext or Razor Pages
I think adding these features to webpages make it complicated. msft forget webpages goal so we move...

Curt Smith 27/07/2016 20:38
In response to ASP.NET Web Pages vNext or Razor Pages
I am only slightly disappointed to hear that WebMatrix is officially dead, because I suspected this...

Darshan Raj L G 27/07/2016 13:20
In response to Implementing SQL Server Full-Text Search In An ASP.NET MVC Web Application With Entity Framework
I though it would be more helpful for somebody who wants to work with Entity Framework... please EF...

Satyabrata 25/07/2016 08:09
In response to Loading ASP.NET Core MVC Views From A Database Or Other Location
Very Interesting!!...

Jerrie Pelser 23/07/2016 05:08
In response to Loading ASP.NET Core MVC Views From A Database Or Other Location
Very cool concept Mike!...