Today, I was rewriting an old ASP.NET MVC5 Demo project to ASP.NET Core, and found that the way we used to read Web.config by ConfigurationManager.AppSettings[] is no longer working. .NET Core has many new ways to achieve this. I picked one that suitable for my project. Here is how I do it.

The old ASP.NET code:

web.config

...
  <appSettings>
    ...
    <add key="StorageConnectionString" value="DefaultEndpointsProtocol=https;AccountName=YOURACCOUNT;AccountKey=YOURKEY" />
    <add key="AzureStorageAccountContainer" value="YOURCONTAINER" />
   ...
  </appSettings>
...

Controller:

private static CloudBlobContainer GetBlobContainer()
{
    string connectionString = WebConfigurationManager.AppSettings["StorageConnectionString"];
...
        blobClient.GetContainerReference(WebConfigurationManager.AppSettings["AzureStorageAccountContainer"]);
    return container;
}

This is how we used to read web.config in ASP.NET. If you want to know more, please refer to my post《如何高逼格读取Web.config中的AppSettings》, which shows how to use a strong type configuration item. Now, in ASP.NET Core, we can do the same.

First, ASP.NET Core settings file is called appsettings.json, instead of web.config. In an ASP.NET Core application, web.config is only used by IIS when deployed to a Windows Server. It has nothing to do with ASP.NET Core itself.

The defination of appsettings.json is like:

{
    "Logging": {
        "IncludeScopes": false,
        "LogLevel": {
            "Default": "Debug",
            "System": "Information",
            "Microsoft": "Information"
        }
    }
}

To add our own configuration:

{
    "Logging": {
        "IncludeScopes": false,
        "LogLevel": {
            "Default": "Debug",
            "System": "Information",
            "Microsoft": "Information"
        }
    },
    "AppSettings": {
        "StorageConnectionString": "DefaultEndpointsProtocol=https;AccountName=YOURACCOUNTNAME;AccountKey=YOURKEY",
        "AzureStorageAccountContainer": "YOURCONTAINERNAME"
    }
}

Next, create a new C# Class, and add the properties that matches your configuration file:

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

    public string AzureStorageAccountContainer { get; set; }
}

Open Startup.cs, replace the code of ConfigureServices

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddOptions();
    services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
    services.AddMvc();
}

Remember to install this package:

Microsoft.Extensions.Options.ConfigurationExtensions

add this to project.json:

"dependencies": {
...
    "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",
...
},

Configuration这个对象,在ASP.NET Core Web Applictaion的默认模板里已经自动撸好了,代码如下:

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
        .AddEnvironmentVariables();
    Configuration = builder.Build();
}

public IConfigurationRoot Configuration { get; }

Use Configuration.GetSection("AppSettings") to read the "AppSettings" node from the json file.

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

What this line of code does is whenever you use the type AppSettings in your code, it will return an instance of Configuration.GetSection("AppSettings"). .NET Core will do the type converting and mapping, which is the same as I did in my 《如何高逼格读取Web.config中的AppSettings》

Finally, in your Controller, modify the constructor like this:

private AppSettings AppSettings { get; set; }

public HomeController(IOptions<AppSettings> settings)
{
    AppSettings = settings.Value;
}

Then, we can use the strong type configuration values like this:

private CloudBlobContainer GetBlobContainer()
{
    string connectionString = AppSettings.StorageConnectionString;
    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
    CloudBlobContainer container =
        blobClient.GetContainerReference(AppSettings.AzureStorageAccountContainer);
    return container;
}