[英]How to set Environment Name (IHostingEnvironment.EnvironmentName)?
默認的ASP.NET Core Web項目在Startup.cs
包含這樣的行:
if (string.Equals(env.EnvironmentName, "Development", StringComparison.OrdinalIgnoreCase))
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage(ErrorPageOptions.ShowAll);
}
else
{
app.UseExceptionHandler("/Home/Error");
}
據我了解,EnvironmentName是一種處理開發/生產環境的新方法。 但它在發布版本配置上沒有變化。 那么設置不同的EnvironmentName
的方法是什么?
我可以想象它應該在“命令”中設置為服務器的參數。
那么設置不同的EnvironmentName的方法是什么?
設置ASPNETCORE_ENVIRONMENT
環境變量。
設置該環境變量的方法有很多種。 其中包括launchSettings.json
配置文件和其他特定於環境的方法 。 這里有些例子。
從控制台:
// PowerShell
> $env:ASPNETCORE_ENVIRONMENT="Development"
// Windows Command Line
> SET ASPNETCORE_ENVIRONMENT=Development
// Bash
> ASPNETCORE_ENVIRONMENT=Development
從Azure Web App的應用程序設置:
我可以想象它應該在“命令”中設置為服務器的參數。
那是真實的。 在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
dnx . web
命令行, ASPNET_ENV
會production
。
該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
仍然支持Hosting:Environment
,但會生成不推薦的消息警告。
https://docs.asp.net/en/latest/migration/rc1-to-rtm.html
默認值為“生產” 並在此處設置。
您可以通過定義名為ASPNET_ENV
的環境變量來設置環境。 例如,如果您想要Release SET ASPNET_ENV=Release
。
如果您將ASPNET_ENV=Release
作為參數傳遞給命令,它也可能有效,但我現在無法檢查它。
以下是它的實現方式: https : //github.com/aspnet/Hosting/blob/217f9ca3d3ccf59ea06e6555820974ba9c3b5932/src/Microsoft.AspNet.Hosting/ConfigureHostingEnvironment.cs
launchsettings.json
在Properties> 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"
}
}
}
}
我有同樣的問題。 為了獨立於環境變量和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
文件將在相應項目的Properties文件夾中創建(或更新),因此很容易將此文件保存到源控件解決方案中並在開發人員之間共享(與使用SET
其他解決方案相反) / SETX
命令)
注意:默認情況下,最新的ASP.NET Core將環境設置為Production。 因此,您只需要在VS中將ASPNETCORE_ENVIRONMENT
設置為Development
以進行調試(參見上面的屏幕截圖)。 當然,當您希望在本地使用Staging環境運行代碼時,應將ASPNETCORE_ENVIRONMENT
設置為Staging
。 最后,當您想在生產環境中運行它時,只需刪除此變量或將值設置為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
當您查看IHostingEnviroment變量類型時,它是Microsoft.AspNet.Hosting.HostingEnvrioment。
現在有兩種方法可以根據動態配置進行更改。
您可以實現IHostingEnvironment接口並使用您自己的類型。 您可以從Config文件中讀取值。
您可以使用界面您可以直接在此處更新該變量。
public Startup(IHostingEnvironment env) { // Setup configuration sources. Configuration = new Configuration() .AddJsonFile("config.json").AddEnvironmentVariables(); Configuration.Set("ASPNET_ENV","Your own value"); }
如果查看ConfigureServices中的服務,默認情況下會有服務配置列表,其中一個是IConfigureHostingEnviroment。 默認實現是內部類,因此您無法直接訪問,但您可以設置上面的鍵ASPNET_ENV並讀取該值。
在Azure上,只需在Web應用程序配置頁面上設置ASPNET_ENV環境變量。
使用您自己的IIS或其他托管提供商 - 修改web.config以包含“web”命令的參數:
<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>
在開發期間(如果您可以修改源代碼),您還可以在項目的根目錄中創建名為Microsoft.AspNet.Hosting.json的文件並設置ASPNET_ENV變量。
{“ASPNET_ENV”:“測試”}
如果您需要在不更改代碼的情況下進行設置 - 從項目源文件夾根目錄的命令提示符處輸入:
set ASPNET_ENV=Debug
在VsCode中,將以下內容添加到launch.json中
{
"version": "0.2.0",
"configurations": [
{
...
"env": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
...
]
}
這是在VS2017中設置和切換ASPNETCORE_ENVIRONMENT變量的另一種方法(@ clark-wu回答的附加說明):
注意:在我的情況下,launchSettings.json有兩個配置文件:“IISExpress”和“Project”,其中定義了ASPNETCORE_ENVIRONMENT。
{
"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_ENVIRONMENT設置為任何值,但框架支持三個值:開發,暫存和生產。 如果未設置ASPNETCORE_ENVIRONMENT,則默認為Production。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.