Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core MVC App Settings

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?

like image 758
Mi6u3l Avatar asked Apr 17 '17 09:04

Mi6u3l


People also ask

What is the configuration file for ASP.NET MVC core app?

ASP.NET MVC configuration In ASP.NET apps, configuration uses the built-in . NET configuration files, web. config in the app folder and machine. config on the server.

Does .NET Core support app config?

Application configuration in ASP.NET Core is performed using one or more configuration providers. Configuration providers read configuration data from key-value pairs using a variety of configuration sources: Settings files, such as appsettings. json.

What is Appsetting json in ASP.NET Core?

The appsettings. json file is generally used to store the application configuration settings such as database connection strings, any application scope global variables, and much other information.


2 Answers

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.

like image 186
tomRedox Avatar answered Sep 29 '22 08:09

tomRedox


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"

like image 33
Mi6u3l Avatar answered Sep 29 '22 08:09

Mi6u3l