179
votes

I've got a method that reads settings from my config file like this:

var value = ConfigurationManager.AppSettings[key];

It compiles fine when targeting .NET Standard 2.0 only.

Now I need multiple targets, so I updated my project file with:

<TargetFrameworks>netcoreapp2.0;net461;netstandard2.0</TargetFrameworks>

But now, the compilation fails for netcoreapp2.0 with the following error message:

Error   CS0103  The name 'ConfigurationManager' does not exist in the current context   (netcoreapp2.0)

Separately, I created a new .NET Core 2.0 console application (only targeting .NET Core 2.0 this time), but likewise there seems to be no ConfigurationManager under the namespace System.Configuration.

I'm quite confused because it's available under .NET Standard 2.0, so I would expect it to be available in .NET Core 2.0, as .NET Core 2.0 is .NET Standard 2.0 compliant.

What am I missing?

6
You're probably missing this. (Note that a .NET Standard target covers both .NET and .NET Core, so there's really no need to build those separately as well.)Jeroen Mostert
Thanks @JeroenMostert, adding the NuGet package System.Configuration.ConfigurationManager resolved the problem. Now, this is probably a separate question but how is .NET Core 2.0 deemed .NET Standard 2.0 compliant if one needs to add packages to polyfill the missing bits?Alex Sanséau
".NET Standard 2.0 compliant" means "if you build this to target .NET Standard 2.0, it will run on .NET Core 2.0 (among other platforms)". It does not mean "if you build this to target .NET Core 2.0, all the .NET Standard 2.0 APIs will be available without further action". If you build this to .NET Standard 2.0 and it won't run on .NET Core, then you have cause for complaint, but I think this is just going to work. (I haven't tested it, though.)Jeroen Mostert
@AlexSanséau The NuGet packages aren't poly-fills. When starting work on .NET Core Microsoft took the decision of making the APIs opt-in, meaning that your applications have a smaller footprint. I would recommend taking some time and watching the videos that Immo Landwerth has created on .NET Standard (youtube.com/…) - he's the PM on the .NET Standard teamJamie Taylor
RE: It compiles fine when targeting .NET Standard 2.0 only - this cannot be correct, because ConfigurationManager is not part of .NET Standard (so far this is true up to v.2.1).G. Stoynev

6 Answers

313
votes

Yes, ConfigurationManager.AppSettings is available in .NET Core 2.0 after referencing NuGet package System.Configuration.ConfigurationManager.

Credits goes to @JeroenMostert for giving me the solution.

24
votes

I installed System.Configuration.ConfigurationManager from Nuget into my .net core 2.2 application.

I then reference using System.Configuration;

Next, I changed

WebConfigurationManager.AppSettings

to ..

ConfigurationManager.AppSettings

So far I believe this is correct. 4.5.0 is typical with .net core 2.2

I have not had any issues with this.

13
votes

Once you have the packages setup, you'll need to create either an app.config or web.config and add something like the following:

<configuration>
  <appSettings>
    <add key="key" value="value"/>
  </appSettings>
</configuration>
10
votes

The latest set of guidance is as follows: (from https://docs.microsoft.com/en-us/azure/azure-functions/functions-dotnet-class-library#environment-variables)

Use:

System.Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Process);

From the docs:

public static class EnvironmentVariablesExample
{
    [FunctionName("GetEnvironmentVariables")]
    public static void Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer, ILogger log)
    {
        log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
        log.LogInformation(GetEnvironmentVariable("AzureWebJobsStorage"));
        log.LogInformation(GetEnvironmentVariable("WEBSITE_SITE_NAME"));
    }

    public static string GetEnvironmentVariable(string name)
    {
        return name + ": " +
            System.Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Process);
    }
}

App settings can be read from environment variables both when developing locally and when running in Azure. When developing locally, app settings come from the Values collection in the local.settings.json file. In both environments, local and Azure, GetEnvironmentVariable("<app setting name>") retrieves the value of the named app setting. For instance, when you're running locally, "My Site Name" would be returned if your local.settings.json file contains { "Values": { "WEBSITE_SITE_NAME": "My Site Name" } }.

The System.Configuration.ConfigurationManager.AppSettings property is an alternative API for getting app setting values, but we recommend that you use GetEnvironmentVariable as shown here.

0
votes

You can use Configuration to resolve this.

Ex (Startup.cs):

You can pass by DI to the controllers after this implementation.

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

        Configuration = builder.Build();

    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {

        var microserviceName = Configuration["microserviceName"];

       services.AddSingleton(Configuration);

       ...
    }
-2
votes

I know it's a bit too late, but maybe someone is looking for easy way to access appsettings in .net core app. in API constructor add the following:

public class TargetClassController : ControllerBase
{
    private readonly IConfiguration _config;

    public TargetClassController(IConfiguration config)
    {
        _config = config;
    }

    [HttpGet("{id:int}")]
    public async Task<ActionResult<DTOResponse>> Get(int id)
    {
        var config = _config["YourKeySection:key"];
    }
}