简体   繁体   中英

.net core 3 c# 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 its meant to do that already isnt it? I know this has changed in v3 in v2 you did need to build the configuration.

Any help appreciated!

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"];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM