.NET Core 2.0에서 ConfigurationManager.AppSettings를 사용할 수 있습니까? 함께 컴파일이 실패 합니다. Error

구성 파일에서 다음과 같이 설정을 읽는 방법이 있습니다.

var value = ConfigurationManager.AppSettings[key];

.NET Standard 2.0만을 대상으로 할 때 잘 컴파일됩니다.

이제 여러 대상이 필요하므로 프로젝트 파일을 다음과 같이 업데이트했습니다.

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

그러나 이제 netcoreapp2.0다음 오류 메시지와 함께 컴파일이 실패 합니다.

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

별도로, 나는 새로운 .NET Core 2.0 콘솔 응용 프로그램을 만들었지 만 (이번에는 .NET Core 2.0만을 대상으로 함) ConfigurationManager네임 스페이스 에는없는 것처럼 보입니다 System.Configuration.

.NET Standard 2.0에서 사용할 수 있기 때문에 혼란 스럽습니다. 따라서 .NET Core 2.0은 .NET Standard 2.0과 호환되므로 .NET Core 2.0에서 사용할 수있을 것으로 기대합니다.

내가 무엇을 놓치고 있습니까?



답변

예, ConfigurationManager.AppSettingsNuGet 패키지를 참조한 후 .NET Core 2.0에서 사용할 수 있습니다 System.Configuration.ConfigurationManager.

크레딧은 저에게 해결책을 주신 @JeroenMostert에게갑니다.


답변

System.Configuration.ConfigurationManagerNuget에서 .net core 2.2 응용 프로그램으로 설치 했습니다.

그런 다음 참조 using System.Configuration;

다음으로, 나는 바꿨다

WebConfigurationManager.AppSettings

to ..

ConfigurationManager.AppSettings

지금까지 나는 이것이 맞다고 믿는다. 4.5.0 is typical with .net core 2.2

나는 이것에 아무런 문제가 없었다.


답변

패키지가 설정되면 app.config 또는 web.config를 생성하고 다음과 같은 것을 추가해야합니다.

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


답변

다음지도의 최신 집합은 다음과 같습니다 (에서 https://docs.microsoft.com/en-us/azure/azure-functions/functions-dotnet-class-library#environment-variables )

사용하다:

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

문서에서 :

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

로컬에서 개발하거나 Azure에서 실행할 때 환경 변수에서 앱 설정을 읽을 수 있습니다. 로컬로 개발할 때 앱 설정은 local.settings.json 파일 의 Values컬렉션에서 가져옵니다 . 로컬 및 Azure 환경 모두 에서 명명 된 앱 설정 값을 검색합니다. 예를 들어 로컬에서 실행중인 경우 local.settings.json 파일에가 포함되어 있으면 “내 사이트 이름”이 반환됩니다 .GetEnvironmentVariable("<app setting name>"){ "Values": { "WEBSITE_SITE_NAME": "My Site Name" } }

System.Configuration.ConfigurationManager.AppSettings의 속성은 응용 프로그램의 설정 값을 얻기위한 대안 API이지만, 우리는 당신이 사용하는 것이 좋습니다 GetEnvironmentVariable다음과 같이.


답변

구성을 사용하여이 문제를 해결할 수 있습니다.

예 (Startup.cs) :

이 구현 후에 DI를 통해 컨트롤러로 전달할 수 있습니다.

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

       ...
    }


답변