30

Having trouble figuring out how to read appsettings.json values outside of the startup.cs. What I would like to do is, for instance, is in the _Layout.cshtml, add the site name from the config:

For example:

ViewData["SiteName"] = Configuration.GetValue<string>("SiteSettings:SiteName");

Or even better:

public class GlobalVars {
    public static string SiteName => Configuration.GetValue<string>("SiteSettings:SiteName");
}

Here's my code thus far:

[appsettings.json]

"SiteSettings": {
    "SiteName": "MySiteName"
}

[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)
        .AddEnvironmentVariables();
    Configuration = builder.Build();

    var siteName = Configuration.GetValue<string>("SiteSettings:SiteName");
}

public IConfigurationRoot Configuration { get; }

Maybe I'm reading the docs wrong, but I can't seem to expose the Configuration object outside of the Startup class.

1

2 Answers 2

59

In your Startup.cs

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<IConfiguration>(Configuration);
    }

then in your controller:

public class ValuesController : Controller
{
    IConfiguration configuration;

    public ValuesController(IConfiguration configuration)
    {
        this.configuration = configuration;
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

That works well. Do you know of a way of referencing that statically in something like a GlobalVars.cs so I don't have to declare this at the top of each controller?
You could create a singleton and expose the Configuration property from it. Make sure it's always the same instance. Then you can use it in the Startup instead of creating a new Configuration instance there. This will make the Property available to others layers.
That's actually an abuse of IConfiguration. The controller shouldn't care about the configuration middleware. It shouldn't require it to be up and running just to pass a single setting. It's DI that should register and inject the settings to the controller, perhaps in the form of IOption<> objects
0

Wanted to add an update to this post since I ran into it while searching for Dot Net Core 8 MVC: You now add the following to the builder in Program.cs (which replaced Startup.cs):

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

// Add IConfiguration to the container
builder.Services.AddSingleton(builder.Configuration);

var app = builder.Build();

Then add the following to the top of your controller with the logger:

private readonly ILogger<HomeController> _logger;
private readonly IConfiguration _appsettings;
  
      public HomeController(ILogger<HomeController> logger, IConfiguration appsettings)
        {
            _logger = logger;
            _appsettings = appsettings;
        }    

After adding these you can then access appsettings.json values in array format as follows:

var businessLocation = _appsettings["Locations:101"];

Where appsettings.json format is as follows (and get the value 1):

"Locations": {
  "101": "1",
  "202": "2",
  "303": "3"
},

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.