Rolf Herbert
Rolf Herbert

Reputation: 75

C# .NET Core Razor pages appsettings values not accessible

When I set up a .NET Core v3 Razor web application the startup.cs file contains what I should need in order to access settings/values from the appsettings.json file;

public IConfiguration Configuration { get; set; }

public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

According to the docs I should then be able to use;

Configuration["mysetting:variable"]

Anywhere to access it. However I get the build error 'The name 'Configuration' does not exist in the current context'.

In order to solve this I have manually built the configuration using;

ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetSection("mysetting")["variable"]

but it's meant to do that already isn't it? I know this has changed in v3 in v2 you did need to build the configuration.

Upvotes: 0

Views: 1461

Answers (1)

Peter Sandor
Peter Sandor

Reputation: 143

Try adding this @inject statement to the top of your razor page:

@inject Microsoft.Extensions.Configuration.IConfiguration Configuration

After that, you should be able to access the config settings using this injected field:

var mySettingVariable = Configuration["mysetting:variable"];

Upvotes: 1

Related Questions