ChatGPT解决这个技术问题 Extra ChatGPT

Is ConfigurationManager.AppSettings available in .NET Core 2.0?

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?

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.)
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?
".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.)
@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 team
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).

A
Alex Sanséau

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.


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, 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: <add key="YourSetting" value="YourValue" />
@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.
@JanDeutschl, it should go into the appSettings section of your web.config or app.config, as you would do for a traditional .NET project.
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?
T
Tom Stickel

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.


One of the easy fixes to do for migration. Some of the others are not so fun :/
did you also create a web.config file?
it not works for me (.net core 3.1). it has no any settings data if access
@Arteny - I never tested it with 3.1 - I installed 3.1 and played with it at home - but my current client is not wanting to upgrade anytime soon.
S
Sharpiro

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>

N
Nate Radebaugh

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("") 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.


For anyone trying this out, you get syntax similar to the Microsoft example by declaring this: using static System.Environment;
A highlight of this approach, System.Environment.GetEnvironmentVariable, is that you remove the Nuget package/dependency for System.Configuration.ConfigurationManager
F
Frederico Freitas

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

       ...
    }

H
Hamdan Dabbas

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