207

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?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Alex Sanséau
  • 8,250
  • 5
  • 20
  • 25
  • 16
    You're probably missing [this](https://www.nuget.org/packages/System.Configuration.ConfigurationManager/). (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 Dec 01 '17 at 10:59
  • 1
    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 Dec 01 '17 at 11:31
  • 2
    ".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 Dec 01 '17 at 11:34
  • 4
    @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 (https://www.youtube.com/watch?v=YI4MurjfMn8&list=PLRAdsfhKI4OWx321A_pr-7HhRNk7wOLLY) - he's the PM on the .NET Standard team – Jamie Taylor Dec 01 '17 at 11:43
  • 1
    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 Feb 19 '20 at 04:23

7 Answers7

348

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.

Alex Sanséau
  • 8,250
  • 5
  • 20
  • 25
  • 3
    Can you post code from your config file? I'm trying to figure out how/where I set a global variable in .NET Core 2.0 – egmfrs Apr 27 '18 at 10:16
  • 1
    @egmfrs, would you mind to re-phrase please? Global variables would exist in the form of static properties of a class. Config files contains application settings is their usual format: `` – Alex Sanséau Apr 30 '18 at 13:01
  • 3
    @AlexSanséau, I'm trying to figure out where can I set the values for AppSettings. web.config or appsettings.json doesn't work. Could you give an example where to set AppSettings? Thanks. – Jan Deutschl Sep 26 '18 at 12:26
  • 2
    @JanDeutschl, it should go into the appSettings section of your web.config or app.config, as you would do for a traditional .NET project. – Alex Sanséau Oct 02 '18 at 08:27
  • 9
    I am bit confused. This does list `.NET Framework 4.6` as a dependency. Does that mean that my` .NET Core` project is no longer a pure `Core` project? – James Poulose Nov 24 '18 at 23:51
  • @JamesPoulose No, This is for Core, but also works backwards to 4.6.1 I use this in my .net core 2.2 projects and inside a EF Core 2.2.x class that implements the DbContext from `Microsoft.EntityFrameworkCore` – Tom Stickel Apr 10 '19 at 00:15
  • 2
    How do you load appsettings.json application settings into ConfigurationManager? This answer seems confusing, as it's using ConfigurationManager but still using a Web.Config (which isn't what you're supposed to use in ASP.NET Core.) – Justin May 02 '19 at 01:26
  • @Justin, the answer does not mention web.config. Also, not all .NET Core applications are ASP.NET Core application (one can create console app as well). – Alex Sanséau May 15 '19 at 09:04
  • @AlexSanséau You mention XML yourself the only way to do this is in a .config file instead of the .net core variant. This seems more like a work around than a fix. – Jean-Paul Dec 31 '19 at 10:22
29

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.

Tom Stickel
  • 19,633
  • 6
  • 111
  • 113
15

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>
Sharpiro
  • 2,305
  • 2
  • 18
  • 27
12

The latest set of guidance is as follows: (from https://learn.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.

Nate Radebaugh
  • 1,044
  • 2
  • 20
  • 29
  • For anyone trying this out, you get syntax similar to the Microsoft example by declaring this: `using static System.Environment;` – MattMakes Jul 16 '19 at 23:44
  • A highlight of this approach, `System.Environment.GetEnvironmentVariable`, is that you remove the Nuget package/dependency for `System.Configuration.ConfigurationManager` – Don Cheadle Jan 14 '22 at 16:52
2

I used below code example. Also this is so convenient way.

using Microsoft.Extensions.Configuration;
using System.IO;

namespace DemoWeppApp
{
    public static class StaticConfigurationManager
    {
        public static IConfiguration AppSetting { get; }
        static StaticConfigurationManager()
        {
            AppSetting = new ConfigurationBuilder()
                    .SetBasePath(Directory.GetCurrentDirectory())
                    .AddJsonFile("appsettings.json")
                    .Build();
        }
    }
}

And then I can use easly in any static class like this

StaticConfigurationManager.AppSetting["conf_name"];
Yusif Karimov
  • 400
  • 5
  • 8
0

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);

       ...
    }
-1

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"];
    }
}
Hamdan Dabbas
  • 537
  • 1
  • 5
  • 11