ASP.NET Core MVC App Settings
Asked Answered
H

2

6

I'm trying to use configuration variables on my ASP.NET Core MVC project.

This is where I've got so far:

  1. Created an appsettings.json
  2. Created an AppSettings class
  3. Now I'm trying to inject it on the ConfigureServices, but my Configuration class is either not recognized or when using the full reference: "Microsoft.Extensions.Configuration" the GetSection Method is not recognized, i.e.

Configuration class not being recognized

GetSection method not being recognized

Any ideas on how to use this?

Halstead answered 17/4, 2017 at 9:43 Comment(1)
Please note, there is no MVC6, only MVC1-5. It is now called ASP.NET Core 1.x, begins with version 1 to make it clear it's not an successor of MVC5 but a complete rewrite which is not compatible with MVC5 and previous versions of ASP.NET MVCCapsulate
T
9

The whole configuration approach in .NET Core is really flexible, but not at all obvious at the beginning. It's probably easiest to explain with an example:

Assuming an appsettings.json file that looks like this:

{
  "option1": "value1_from_json",

  "ConnectionStrings": {
    "DefaultConnection": "Server=,\\SQL2016DEV;Database=DBName;Trusted_Connection=True"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}

To get the data from appsettings.json file you first need to set up a ConfigurationBuilder in Startup.cs as follows:

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

    if (env.IsDevelopment())
    {
        // For more details on using the user secret store see https://go.microsoft.com/fwlink/?LinkID=532709
        builder.AddUserSecrets<Startup>();
    }

    builder.AddEnvironmentVariables();
    Configuration = builder.Build();

You can then access the configuration directly, but it's neater to create Options classes to hold that data, which you can then have injected into your controller or other classes. Each of those options classes represent a different section of the appsettings.json file.

In this code the connections strings are loaded into a ConnectionStringSettings class and the other option is loaded into a MyOptions class. The .GetSection method gets a particular part of the appsettings.json file. Again, this is in Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    ... other code

    // Register the IConfiguration instance which MyOptions binds against.
    services.AddOptions();

    // Load the data from the 'root' of the json file
    services.Configure<MyOptions>(Configuration);

    // load the data from the 'ConnectionStrings' section of the json file
    var connStringSettings = Configuration.GetSection("ConnectionStrings");
    services.Configure<ConnectionStringSettings>(connStringSettings);

These are the classes that the settings data are loaded into. Note how the property names pair up with the settings in the json file:

public class MyOptions
{
    public string Option1 { get; set; }
}

public class ConnectionStringSettings
{
    public string DefaultConnection { get; set; }
}

Finally, you can then access those settings by injecting an OptionsAccessor into the controller as follows:

private readonly MyOptions _myOptions;

public HomeController(IOptions<MyOptions > optionsAccessor)
{
    _myOptions = optionsAccessor.Value;
    var valueOfOpt1 = _myOptions.Option1;
}

Generally, the whole configurations settings process is pretty different in Core. Thomas Ardal has a good explanation of it on his site here: http://thomasardal.com/appsettings-in-asp-net-core/

There's also a more detailed explanation of Configuration in ASP.NET Core in the Microsoft documentation.

NB: This has all evolved a bit in Core 2, I need to revisit some of the answer above, but in the meantime this Coding Blast entry by Ibrahim Šuta is an excellent introduction with plenty of examples.

NB No. 2: There are a number of configuration mistakes that are easy to make with the above, have a look at this answer if it doesn't behave for you.

Tamelatameless answered 17/4, 2017 at 9:55 Comment(0)
H
1

tomRedox 's answer was highly helpful - Thanks. Also, I've changed the following references to the following versions, to get it working.

"Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.2", "Microsoft.Extensions.Configuration.Json": "1.1.1"

Halstead answered 17/4, 2017 at 12:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.