sourcetip

환경 이름(IHosting Environment) 설정 방법.환경 이름)?

fileupload 2023. 6. 12. 21:49
반응형

환경 이름(IHosting Environment) 설정 방법.환경 이름)?

ASP웹에는 ASP.NET Core 파일에 .Startup.cs:

if (string.Equals(env.EnvironmentName, "Development", StringComparison.OrdinalIgnoreCase))
{
    app.UseBrowserLink();
    app.UseDeveloperExceptionPage(ErrorPageOptions.ShowAll);
}
else
{
    app.UseExceptionHandler("/Home/Error");
}

제가 알기로는 EnvironmentName은 개발/운영 환경을 처리하는 새로운 방법입니다.그러나 릴리스 빌드 구성에서는 변경되지 않습니다.그래서 다른 방법을 설정하는 방법은 무엇입니까?EnvironmentName?

서버에 대한 매개 변수로 "명령"에 설정되어야 한다고 상상할 수 있습니다.

RC2 이후

그렇다면 다른 환경 이름을 설정하는 방법은 무엇입니까?

을 합니다.ASPNETCORE_ENVIRONMENT환경 변수

환경 변수를 설정하는 방법은 여러 가지가 있습니다.여기에는 다음이 포함됩니다.launchSettings.json프로파일 및 기타 환경별 방법.여기 몇 가지 예가 있어요.

콘솔에서:

// PowerShell
> $env:ASPNETCORE_ENVIRONMENT="Development"

// Windows Command Line
> SET ASPNETCORE_ENVIRONMENT=Development

// Bash
> ASPNETCORE_ENVIRONMENT=Development

Azure Web App의 앱 설정에서 다음을 수행합니다.

환경 이름을 Azure로 설정

RC2 이전

서버에 대한 매개 변수로 "명령"에 설정되어야 한다고 상상할 수 있습니다.

그것은 사실이에요.프젝트.json, 추가를 합니다.--ASPNET_ENV production서버에 대한 매개 변수로 사용됩니다.

"commands": {
  "web": "Microsoft.AspNet.Hosting --ASPNET_ENV production --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5001"
}

이제당달때릴이신때▁you를 실행할 때.dnx . web 명행에서령,ASPNET_ENV▁▁be 될 것입니다.production.

관련 ASP.NET 코어 호스팅 소스 코드

WebHostBuilder"ASPNETCORE_"WebHostDefaults.EnvironmentKey만들기 위해서"ASPNETCORE_environment"또한 기존 키도 지원합니다.

WebHostDefaults.cs

namespace Microsoft.AspNetCore.Hosting
{
    public static class WebHostDefaults
    {
        public static readonly string ApplicationKey = "applicationName";
        public static readonly string StartupAssemblyKey = "startupAssembly";

        public static readonly string DetailedErrorsKey = "detailedErrors";
        public static readonly string EnvironmentKey = "environment";
        public static readonly string WebRootKey = "webroot";
        public static readonly string CaptureStartupErrorsKey = "captureStartupErrors";
        public static readonly string ServerUrlsKey = "urls";
        public static readonly string ContentRootKey = "contentRoot";
    }
}

WebHostBuilder.cs

_config = new ConfigurationBuilder()
    .AddEnvironmentVariables(prefix: "ASPNETCORE_")
    .Build();

if (string.IsNullOrEmpty(GetSetting(WebHostDefaults.EnvironmentKey)))
{
    // Try adding legacy environment keys, never remove these.
    UseSetting(WebHostDefaults.EnvironmentKey, 
        Environment.GetEnvironmentVariable("Hosting:Environment") 
        ?? Environment.GetEnvironmentVariable("ASPNET_ENV"));
}

이전 버전과의 호환성

는 경키다사설여정다니됩용하로 됩니다.ASPNETCORE_ENVIRONMENT환경 변수입니다. ASPNET_ENV그리고.Hosting:Environment계속 지원되지만 사용되지 않는 메시지 경고를 생성합니다.

https://docs.asp.net/en/latest/migration/rc1-to-rtm.html

기본값

기본값은 "Production"이며 여기서 설정됩니다.

시작 설정.json

속성 > 시작 설정.json에서

이와 같이:

    {
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:1032/",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Production"
      }
    },
    "WebAppNetCore": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "web": {
      "commandName": "web",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

인 다음과정의은환변정수설환다니합을 정의하여 을 설정합니다.ASPNET_ENV들어 Release 를▁▁you경우▁SET ASPNET_ENV=Release.

합격하면 효과가 있을 수도 있습니다.ASPNET_ENV=Release명령에 대한 매개 변수로 사용할 수 있지만 지금 확인할 수 없습니다.

구현 방법은 다음과 같습니다. https://github.com/aspnet/Hosting/blob/217f9ca3d3ccf59ea06e6555820974ba9c3b5932/src/Microsoft.AspNet.Hosting/ConfigureHostingEnvironment.cs

저도 같은 문제가 있었어요.환경 변수와 web.config에 독립하기 위해 다음과 같이 .json 파일을 만들었습니다(envsettings.json이라고 불렀습니다).

{
  // Possible string values reported below.
  // - Production
  // - Staging
  // - Development
  "ASPNETCORE_ENVIRONMENT": "Staging"
}

그런 다음 Program.cs 에서 다음과 같이 추가했습니다.

public class Program
{
    public static void Main(string[] args)
    {
        var currentDirectoryPath = Directory.GetCurrentDirectory();
        var envSettingsPath = Path.Combine(currentDirectoryPath, "envsettings.json");
        var envSettings = JObject.Parse(File.ReadAllText(envSettingsPath));
        var enviromentValue = envSettings["ASPNETCORE_ENVIRONMENT"].ToString();

        var webHostBuilder = new WebHostBuilder()
            .UseKestrel()
            .CaptureStartupErrors(true)
            .UseSetting("detailedErrors", "true")
            .UseContentRoot(currentDirectoryPath)
            .UseIISIntegration()
            .UseStartup<Startup>();

        // If none is set it use Operative System hosting enviroment
        if (!string.IsNullOrWhiteSpace(enviromentValue)) 
        {
            webHostBuilder.UseEnvironment(enviromentValue);
        }

        var host = webHostBuilder.Build();

        host.Run();
    }
}

기능 2017)을 할 수 있습니다. VS " (debug: VS 2017)"에서 사용할 수 있습니다. ASP 버전에서는 "ASP.NET Core"(RC2)를 .ASPNETCORE_ENVIRONMENT변수.

여기에 이미지 설명 입력

결적으로과,로으,launchSettings.json해당 프로젝트의 속성 폴더에 파일이 생성(또는 업데이트)되므로 이 파일을 소스 제어 솔루션에 유지하고 개발자 간에 공유하는 것이 쉽습니다(다른 솔루션과는 반대).SET/SETXcommands)

참고: 기본적으로 최신 ASP.NET Core는 환경을 운영으로 설정합니다.그래서, 당신은 단지 설정하기만 하면 됩니다.ASPNETCORE_ENVIRONMENTDevelopment디버깅을 위한 VS(위 스크린샷 참조).)스테이징하려면 물론스징환서로코실드다면행설합음정니다야해을려하를컬로경테이에합▁다▁and니▁set를 설정해야 .ASPNETCORE_ENVIRONMENTStaging그리고이을 마막으로운환실경행이면려하변제서오값나로 .Production.

요약하면: 디버그 대화 상자에서 개발, 스테이징 또는 프로덕션 값이 환경을 설정하고 다른 확장이 작동하도록 하는 데 사용되는지 확인하십시오.

ASP.NET Core의 관련 소스 코드도 참조하십시오.

namespace Microsoft.AspNetCore.Hosting
{
  /// <summary>Commonly used environment names.</summary>
  public static class EnvironmentName
  {
    public static readonly string Development = "Development";
    public static readonly string Staging = "Staging";
    public static readonly string Production = "Production";
  }
}

namespace Microsoft.AspNetCore.Hosting
{
  /// <summary>
  /// Extension methods for <see cref="T:Microsoft.AspNetCore.Hosting.IHostingEnvironment" />.
  /// </summary>
  public static class HostingEnvironmentExtensions
  {
    /// <summary>
    /// Checks if the current hosting environment name is "Development".
    /// </summary>
    /// <param name="hostingEnvironment">An instance of <see cref="T:Microsoft.AspNetCore.Hosting.IHostingEnvironment" />.</param>
    /// <returns>True if the environment name is "Development", otherwise false.</returns>
    public static bool IsDevelopment(this IHostingEnvironment hostingEnvironment)
    {
      if (hostingEnvironment == null)
        throw new ArgumentNullException("hostingEnvironment");
      return hostingEnvironment.IsEnvironment(EnvironmentName.Development);
    }

    /// <summary>
    /// Checks if the current hosting environment name is "Staging".
    /// </summary>
    /// <param name="hostingEnvironment">An instance of <see cref="T:Microsoft.AspNetCore.Hosting.IHostingEnvironment" />.</param>
    /// <returns>True if the environment name is "Staging", otherwise false.</returns>
    public static bool IsStaging(this IHostingEnvironment hostingEnvironment)
    {
      if (hostingEnvironment == null)
        throw new ArgumentNullException("hostingEnvironment");
      return hostingEnvironment.IsEnvironment(EnvironmentName.Staging);
    }

    /// <summary>
    /// Checks if the current hosting environment name is "Production".
    /// </summary>
    /// <param name="hostingEnvironment">An instance of <see cref="T:Microsoft.AspNetCore.Hosting.IHostingEnvironment" />.</param>
    /// <returns>True if the environment name is "Production", otherwise false.</returns>
    public static bool IsProduction(this IHostingEnvironment hostingEnvironment)
    {
      if (hostingEnvironment == null)
        throw new ArgumentNullException("hostingEnvironment");
      return hostingEnvironment.IsEnvironment(EnvironmentName.Production);
    }

    /// <summary>
    /// Compares the current hosting environment name against the specified value.
    /// </summary>
    /// <param name="hostingEnvironment">An instance of <see cref="T:Microsoft.AspNetCore.Hosting.IHostingEnvironment" />.</param>
    /// <param name="environmentName">Environment name to validate against.</param>
    /// <returns>True if the specified name is the same as the current environment, otherwise false.</returns>
    public static bool IsEnvironment(this IHostingEnvironment hostingEnvironment, string environmentName)
    {
      if (hostingEnvironment == null)
        throw new ArgumentNullException("hostingEnvironment");
      return string.Equals(hostingEnvironment.EnvironmentName, environmentName, StringComparison.OrdinalIgnoreCase);
    }
  }
}

ASP.NET Core RC2이 변이름다변음로경니다습었되으이로 되었습니다.ASPNETCORE_ENVIRONMENT

예: Windows에서 관리자 권한으로 준비 서버에서 이 명령을 실행할 수 있습니다.

SETX ASPNETCORE_ENVIRONMENT "Staging" /M

이 작업은 한 번만 실행되고 그 후에는 서버가 항상 준비 서버로 간주됩니다.

할 때.dotnet run에 " 해서명에표시니다됩트프프롬령"가 됩니다.Hosting environment: Staging

이 값을 사용하는 위치에서 이 값을 사용한다고 생각하면 정적 값이고 기본값은 개발 값입니다.

https://github.com/aspnet/Hosting/blob/dev/src/Microsoft.AspNet.Hosting/HostingEnvironment.cs

IHostingEnvironment 변수 유형을 보면 Microsoft입니다.AsNet.호스팅.환경 호스팅.

이제 동적 구성에 따라 두 가지 방법으로 변경할 수 있습니다.

  1. IHosting Environment 인터페이스를 구현하고 이에 사용자 고유의 유형을 사용할 수 있습니다.구성 파일에서 값을 읽을 수 있습니다.

  2. 인터페이스를 사용할 수 있습니다. 여기서 직접 변수를 업데이트할 수 있습니다.

    public Startup(IHostingEnvironment env)
    {
    // Setup configuration sources.
    Configuration = new Configuration()
        .AddJsonFile("config.json").AddEnvironmentVariables();
    
    Configuration.Set("ASPNET_ENV","Your own value");    
    }
    

    서비스 구성에서 서비스를 살펴보면 기본적으로 구성된 서비스 목록이 있으며 그 중 하나가 IConfigureHostingEnvironment입니다.기본 구현은 내부 클래스이므로 직접 액세스할 수 없지만 위에 키 ASPNET_ENV를 설정하면 해당 값을 읽을 수 있습니다.

https://github.com/aspnet/Hosting/blob/dev/src/Microsoft.AspNet.Hosting/ConfigureHostingEnvironment.cs

  1. Azure에서는 웹 앱 구성 페이지에서 ASPNET_ENV 환경 변수를 설정하기만 하면 됩니다.

  2. 사용자 자신의 IIS 또는 다른 호스팅 공급자와 함께 - "web" 명령에 대한 인수를 포함하도록 web.config를 수정합니다.

    <configuration>
     <system.webServer>
      <handlers>
        <add name="httpplatformhandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified" />
      </handlers>
      <httpPlatform processPath="..\approot\web.cmd" arguments="--ASPNET_ENV Development" stdoutLogEnabled="false" stdoutLogFile="..\logs\stdout.log" startupTimeLimit="3600"></httpPlatform>
     </system.webServer>
    </configuration>
    
  3. 개발하는 동안(소스 코드를 수정할 수 있는 경우) 마이크로소프트라는 이름의 파일을 생성할 수도 있습니다.프로젝트의 루트에 있는 AsNet.Hosting.json과 ASPNET_ENV 변수를 설정합니다.

    "ASPNET_ENV": "테스트" }

코드를 변경하지 않고 설정해야 하는 경우 - 프로젝트 원본 폴더의 루트에 있는 명령 프롬프트에서 다음을 수행합니다.

set ASPNET_ENV=Debug

VS2017에서 ASPNETCORE_ENERVICEMENT 변수를 설정하고 전환하는 방법이 하나 있습니다(@clark-wu 답변에 대한 추가 참고).

여기에 이미지 설명 입력

참고: launchSettings.json의 경우 두 가지 프로파일이 있습니다. "ASPNETCORE_ENERVICEENMENT가 정의된 "IISpress" 및 "Project".

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:10000/",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "api/entities",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development" // <-- related to IIS Express profile
      }
    },
    "Project": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "api/entities",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Production" // <-- related to Project profile
      },
      "applicationUrl": "http://localhost:10000/"
    }
  }
}

공식 문서:ASPNETCORE_ENERVICEENMENT를 임의의 값으로 설정할 수 있지만 프레임워크에서는 다음 세 가지 값을 지원합니다.개발, 스테이징 및 프로덕션.ASPNETCORE_ENERVICEENMENT가 설정되어 있지 않으면 운영으로 기본 설정됩니다.

VsCode에서 다음을 추가하여 시작합니다.json

{
    "version": "0.2.0",
    "configurations": [
        {
            ...
            "env": {
                "ASPNETCORE_ENVIRONMENT": "Development"
            }
        },
        ...
    ]
}

언급URL : https://stackoverflow.com/questions/28258227/how-to-set-environment-name-ihostingenvironment-environmentname

반응형