gpt4 book ai didi

c# - 如何设置环境名称(IHostingEnvironment.EnvironmentName)?

转载 作者:IT王子 更新时间:2023-10-29 03:45:14 26 4
gpt4 key购买 nike

默认的 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呢?

我可以想象它应该在“命令”中设置为服务器的参数。

最佳答案

RC2之后

So what is the way to set a different EnvironmentName?

设置 ASPNETCORE_ENVIRONMENT 环境变量。

设置环境变量的方法有很多种。其中包括 launchSettings.json 配置文件和 other environment-specific ways .以下是一些示例。

从控制台:

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

// Windows Command Line
> SET ASPNETCORE_ENVIRONMENT=Development

// Bash
> ASPNETCORE_ENVIRONMENT=Development

从 Azure Web 应用程序的应用程序设置:

Set Environment Name in Azure

RC2 之前

I can imagine that it should be set in "Commands" as a parameter for server.

没错。在您的 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"。它还支持遗留 key 。

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

向后兼容性

The environment key is set with the ASPNETCORE_ENVIRONMENT environment variable. ASPNET_ENV and Hosting:Environment are still supported, but generate a deprecated message warning.

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

默认值

默认值为“生产”and is set here.

关于c# - 如何设置环境名称(IHostingEnvironment.EnvironmentName)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28258227/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com