Zoinky
Zoinky

Reputation: 5019

asp.net 5 (mvc6 configuration) not reading from appsettings.json

appsettings.json

{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
  "Default": "Verbose",
  "System": "Information",
  "Microsoft": "Information"
},
"CustomSettings": {
  "UseDataCaching": true
  }
 }
}

option class

public class CustomSettings
{
    public bool UseDataCaching { get; set; }
}

startup.cs

 public void ConfigureServices(IServiceCollection services)
    {
        ...
        services.AddOptions();
        services.Configure<CustomSettings>(Configuration);
        ...
    }

    public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
    {
        // Set up configuration sources.

        var builder = new ConfigurationBuilder()
            .SetBasePath(appEnv.ApplicationBasePath)
            .AddJsonFile("appsettings.json")
            .AddEnvironmentVariables()
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

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

            // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
            builder.AddApplicationInsightsSettings(developerMode: true);
        }

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

controller

 protected IMemoryCache MemoryCache { get; }
    protected IOptions<CustomSettings> CustomSettings { get; set; }
    public HomeController(IMemoryCache cache, IOptions<CustomSettings> customSettings)
    {

        MemoryCache = cache;
        CustomSettings = customSettings;
    }

customSettings.Value.UseDataCaching is always false even though in appsettings.json i have set it to true.

Not sure if i missed something very obvious

EDIT: added startup constructor

USAGE:

     public IActionResult About()
    {
        var isUsingDataCache = CustomSettings.Value.UseDataCaching;
        ViewData["Message"] = "Your application description page.";

        return View();
    }

EDIT: changed the startup to take 2 params

SAMPLE PROJECT DOES NOT WORK http://www.megafileupload.com/a2hn/WebApplication1.zip

Upvotes: 3

Views: 2751

Answers (1)

msmolcic
msmolcic

Reputation: 6567

Not sure how are you creating your Configuration object, but make sure you add appsettings.json file in it's pipeline, also add BasePath for your application. For example:

public static IConfigurationRoot Configuration;

// You can use both IHostingEnvironment and IApplicationEnvironment at the same time.
// Instances of them are being injected at runtime by dependency injection.
public Startup(IHostingEnvironment hostingEnv, IApplicationEnvironment appEnv)
{
    // Set up configuration sources.
    var builder = new ConfigurationBuilder()
        .SetBasePath(appEnv.ApplicationBasePath)
        .AddJsonFile("appsettings.json")
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

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

        // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
        builder.AddApplicationInsightsSettings(developerMode: true);
    }

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

Edit:

Try changing your ConfigureServices method:

services.Configure<CustomSettings>(Configuration); // from this
services.Configure<CustomSettings>(Configuration.GetSection("CustomSettings")); // to this

Edit 2:

Can you try to create your object inside constructor of controller without it being generic type of IOptions like this:

private CustomSettings _customSettings;

public YourControllerName(CustomSettings customSettings)
{
    _customSettings = customSettings;
}

In Startup.cs ConfigureServices method, set:

services.AddSingleton<CustomSettings>();

Then call it like:

public IActionResult About()
{
    var isUsingDataCache = _customSettings.UseDataCaching;
    ViewData["Message"] = "Your application description page.";

    return View();
}

Edit 3:

Your CustomSettings parameter of your json is placed inside Logging parameter. Try changing your json to this:

{
    "Logging": {
        "IncludeScopes": false,
        "LogLevel": {
            "Default": "Verbose",
            "System": "Information",
            "Microsoft": "Information"
        }
    },
    "CustomSettings": {
        "UseDataCaching": true
    }
}

Edit 4:

I actually tried this out. Created fresh new project, replaced default appsettings.json file with data from Edit 3. Inside Startup.cs at the first line of ConfigureServices method I've placed:

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<CustomSettings>(Configuration.GetSection("CustomSettings"));

    ...
}

Finally, I tested it out inside HomeController:

Example

Upvotes: 6

Related Questions