환경 이름 (IHostingEnvironment.EnvironmentName)을 설정하는 방법은 무엇입니까?
기본 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은 Dev / Production 환경을 처리하는 새로운 방법입니다. 그러나 릴리스 빌드 구성에서는 변경되지 않습니다. 그래서 다른 것을 설정하는 방법은 무엇 EnvironmentName
입니까?
서버의 매개 변수로 "Commands"에 설정되어야한다고 상상할 수 있습니다.
launchsettings.json
속성> launchsettings.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"
}
}
}
}
RC2 이후
그렇다면 다른 EnvironmentName을 설정하는 방법은 무엇입니까?
ASPNETCORE_ENVIRONMENT
환경 변수를 설정합니다 .
해당 환경 변수를 설정하는 방법에는 여러 가지가 있습니다. 여기에는 launchSettings.json
프로필 및 기타 환경 별 방법 이 포함됩니다 . 여기 예시들이 있습니다.
콘솔에서 :
// PowerShell
> $env:ASPNETCORE_ENVIRONMENT="Development"
// Windows Command Line
> SET ASPNETCORE_ENVIRONMENT=Development
// Bash
> ASPNETCORE_ENVIRONMENT=Development
Azure Web App의 앱 설정에서 :
RC2 이전
서버의 매개 변수로 "Commands"에 설정되어야한다고 상상할 수 있습니다.
사실입니다. project.json --ASPNET_ENV production
에서 서버의 매개 변수로 추가하십시오 .
"commands": {
"web": "Microsoft.AspNet.Hosting --ASPNET_ENV production --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5001"
}
실행할 때 이제 dnx . web
명령 줄에서 ASPNET_ENV
이 될 것입니다 production
.
관련 ASP.NET Core 호스팅 소스 코드
WebHostBuilder
콤바인 "ASPNETCORE_"
와 함께 WebHostDefaults.EnvironmentKey
확인합니다 "ASPNETCORE_environment"
. 레거시 키도 지원합니다.
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";
}
}
_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" 이며 여기에서 설정됩니다.
라는 환경 변수를 정의하여 환경을 설정합니다 ASPNET_ENV
. 예를 들어 Release 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();
}
}
VS 기능 (예 : VS 2017)을 사용하려는 경우 프로젝트 속성의 디버그 탭에서 환경 변수를 추가 할 수 있습니다. 예를 들어 최신 ASP.NET Core 버전 (RC2 이후)에서는 ASPNETCORE_ENVIRONMENT
변수 를 설정해야 합니다.
결과적으로 해당 프로젝트 launchSettings.json
의 속성 폴더에 파일이 생성 (또는 업데이트) 되므로이 파일을 소스 제어 솔루션에 저장하고 개발자간에 공유하기 쉽습니다 ( SET
/ SETX
명령을 사용 하는 다른 솔루션과 반대 ).
참고 : 기본적으로 최신 ASP.NET Core는 환경을 프로덕션으로 설정합니다. 따라서 디버깅을 위해 VS에서 로 설정 ASPNETCORE_ENVIRONMENT
하면 Development
됩니다 (위의 스크린 샷 참조). 그리고 스테이징 환경에서 로컬로 코드를 실행 ASPNETCORE_ENVIRONMENT
하려면 Staging
. 마지막으로 프로덕션 환경에서 실행하려면이 변수를 제거하거나 값을 Production
.
요약하면 디버그 대화 상자에서 Development , Staging 또는 Production 값이 사용 되는지 ( 'Dev'또는 다른 항목이 아님) 확인하여 환경을 설정하고 다른 확장이 작동하도록합니다.
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
e.g. In Windows you can execute this command on the staging server (with admin rights)
SETX ASPNETCORE_ENVIRONMENT "Staging" /M
This only has be be executed once and after that, the server will always be considered as the staging server.
When you do a dotnet run
in the command prompt on that server you will see Hosting environment: Staging
If you are thinking that from where it takes this value then as this moment it is static and default value is development.
https://github.com/aspnet/Hosting/blob/dev/src/Microsoft.AspNet.Hosting/HostingEnvironment.cs
When you look at IHostingEnviroment variable type then it is Microsoft.AspNet.Hosting.HostingEnvrioment.
There are two ways you can now change as per dynamic configuration.
You can implement IHostingEnvironment interface and use your own type for that. You can read value from Config file.
You can use interface You can update that variable directly over here.
public Startup(IHostingEnvironment env) { // Setup configuration sources. Configuration = new Configuration() .AddJsonFile("config.json").AddEnvironmentVariables(); Configuration.Set("ASPNET_ENV","Your own value"); }
If you look at services in ConfigureServices there is list of service configure by default and one of them is IConfigureHostingEnviroment. Default implementation is internal class so you can not directly access but you can set above key ASPNET_ENV and it read that value.
On Azure just set ASPNET_ENV environment variable on web app configuration page.
With your own IIS or other hosting providers - modify web.config to include arguments for "web" command:
<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>
During development (if you can modify source code), you can also create file named Microsoft.AspNet.Hosting.json in a root of your project and set the ASPNET_ENV variable.
{ "ASPNET_ENV": "Test" }
if you need to set this without changing code - from the command prompt at the root of the project source folder type:
set ASPNET_ENV=Debug
In VsCode add the following to launch.json
{
"version": "0.2.0",
"configurations": [
{
...
"env": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
...
]
}
Here is one more way to set and switch ASPNETCORE_ENVIRONMENT variable in VS2017 (addtional note to @clark-wu answer):
Note: launchSettings.json has two profiles in my case: "IISExpress" and "Project" where ASPNETCORE_ENVIRONMENT is defined.
{
"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/"
}
}
}
Official documentation: You can set ASPNETCORE_ENVIRONMENT to any value, but three values are supported by the framework: Development, Staging, and Production. If ASPNETCORE_ENVIRONMENT isn't set, it defaults to Production.
'Nice programing' 카테고리의 다른 글
문자열에 배열의 값이 포함되어 있는지 확인 (0) | 2020.11.20 |
---|---|
MongoDb : $ push / $ addtoset의 차이점 (0) | 2020.11.20 |
네임 스페이스가있는 XPath 선택 노드 (0) | 2020.11.20 |
클래스 매핑 오류 : 'T'는 매개 변수가없는 공용 생성자가있는 비추 상 유형이어야합니다. (0) | 2020.11.20 |
MySQL의 필드 값과 함께 LIKE % .. % 사용 (0) | 2020.11.20 |