0
votes

I am trying to access values in my config.json file, but it is returning null values in my controllers and when testing in Startup.cs.

In Startup.cs

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

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

public void ConfigureServices(IServiceCollection services)
{
  /*...

  ...*/
    services.AddOptions();
    services.Configure<AppSettings>(Configuration.GetSection("MicrosoftAzureStorage"));

In the Controller

public class TestController : Controller
{
    private string _token;

    public IActionResult Index()
    {
        return View();
    }

    public TestController(IOptions<AppSettings>settings)
    {
        _token = settings.Value.token; //returns Null
    }

AppSettings.cs

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

}

Config.json

{
    "MicrosoftAzureStorage": 
    {
        "AzureStorageConnectionString": "RandomConnectionString"
    }
}
3

3 Answers

0
votes

You are adding JsonFiles without knowing that they are really present.

.AddJsonFile("config.json", optional: true, reloadOnChange: true)

If you change optional: true to false then you'll probably get an exception. Since I am missing one piece of information, publishOptions in Project.json I cannot be sure. Check publishOptions, you may have to add appsettings.json:

  "publishOptions": {
    "include": [
      "wwwroot",
      "appsettings.json",
      "web.config"
    ]
  },
0
votes

The property name has to match the key name in the json file. See similar example here: Adding loading configuration into inject dependencies in asp.net core

0
votes

Snippet of code I have been using in my application.

In startup.cs

 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)
            .AddJsonFile("secondary.json", optional: false, reloadOnChange: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();
    }

In controller method or helper class.

var builder = new ConfigurationBuilder();
builder.AddJsonFile(Directory.GetCurrentDirectory() + "/secondary.json");
var configuration = builder.Build();
var myValue = configuration["MicrosoftAzureStorage:AzureStorageConnectionString"];