Como definir o nome do ambiente (Iosting Environment.Nome do ambiente)?
predefinição ASP.NET o projecto web principal contém tais linhas em Startup.cs
:
if (string.Equals(env.EnvironmentName, "Development", StringComparison.OrdinalIgnoreCase))
{
app.UseBrowserLink();
app.UseErrorPage(ErrorPageOptions.ShowAll);
}
else
{
app.UseErrorHandler("/Home/Error");
}
tanto quanto sei, o EnvironmentName é uma nova forma de lidar com o Dev/Production environment. Mas não muda na configuração de compilação de lançamento. Então, qual é a maneira de definir um diferente EnvironmentName
?
Eu posso imaginar que ele deve ser definido em "comandos" como um parâmetro para o servidor.
11 answers
Lançadores.json
At Properties > launchsettings.json
Assim: {
"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"
}
}
}
}
Após RC2
Então, qual é a maneira de definir um outro nome de ambiente?
Fixar a variável ambiental ASPNETCORE_ENVIRONMENT
.
launchSettings.json
e outras formas específicas do ambiente. Aqui estão alguns exemplos.
De uma consola:
// PowerShell
> $env:ASPNETCORE_ENVIRONMENT="Development"
// Windows Command Line
> SET ASPNETCORE_ENVIRONMENT=Development
// Bash
> ASPNETCORE_ENVIRONMENT=Development
De uma aplicação Azure Web:
Antes de RC2
Isso é verdade. No teu projecto.json, adicionePode imaginar que ele deve ser definido em "comandos" como um parâmetro para o servidor.
--ASPNET_ENV production
como um parâmetro para o servidor.
"commands": {
"web": "Microsoft.AspNet.Hosting --ASPNET_ENV production --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5001"
}
Agora, quando correres dnx . web
da linha de comandos, ASPNET_ENV
será production
.
Relevante ASP.NET código-fonte de hospedagem principal
O WebHostBuilder
combina "ASPNETCORE_"
com {[12] } para fazer "ASPNETCORE_environment"
. Também apoia o legado chave.
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"));
}
Compatibilidade Retroactiva
A chave de ambiente é definida com a variável de ambiente
ASPNETCORE_ENVIRONMENT
.ASPNET_ENV
eHosting:Environment
ainda são suportados, mas geram um aviso de mensagem desactualizado.
Https://docs.asp.net/en/latest/migration/rc1-to-rtm.html
Valor Por Omissão
O valor por omissão é "produção" e está definido aqui.
Define o ambiente definindo uma variável de ambiente chamada ASPNET_ENV
.
Por exemplo, se você quiser liberar SET ASPNET_ENV=Release
.
Também pode funcionar se passar {[[2]} como parâmetro para os comandos, mas não posso verificá-lo agora.
Eis como é implementado: https://github.com/aspnet/Hosting/blob/217f9ca3d3ccf59ea06e6555820974ba9c3b5932/src/Microsoft.AspNet.Hosting/ConfigureHostingEnvironment.cs
{
// Possible string values reported below.
// - Production
// - Staging
// - Development
"ASPNETCORE_ENVIRONMENT": "Staging"
}
Então no programa.cs I added:
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();
}
}
On Azure just set ASPNET_ env variável de ambiente na página de configuração da aplicação web.
-
Com o seu próprio IIS ou outros fornecedores de hospedagem-modifique a web.configuração a incluir argumentos para o comando "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>
-
Durante o desenvolvimento (se puder modificar o código-fonte), Poderá também criar um ficheiro chamado Microsoft.AspNet.Hospedagem.json numa raiz do seu projecto e defina a variável ASPNET_ENV.
{ "ASPNET_ENV": "Teste" }
Em {[1] } o nome da variável foi alterado para ASPNETCORE_ENVIRONMENT
Por exemplo, no Windows, poderá executar este comando no servidor de paragem (com direitos de administração)
SETX ASPNETCORE_ENVIRONMENT "Staging" /M
Isto só tem de ser executado uma vez e depois disso, o servidor será sempre considerado como o servidor de staging.
Quando fizer um dotnet run
na linha de comandos nesse servidor, irá ver Hosting environment: Staging
Se preferir usar as funcionalidades VS (por exemplo, VS 2017), é possível adicionar variáveis de Ambiente na página de depuração das propriedades do projecto. Por exemplo, no último ASP.NET as versões principais (a seguir ao RC2) deverá definir a variável ASPNETCORE_ENVIRONMENT
.
Como resultado, o ficheiro launchSettings.json
será criado (ou actualizado) na pasta propriedades do projecto correspondente, por isso será fácil persistir este ficheiro na sua solução de controlo de origem e partilhar entre programadores (em oposição a outras soluções com SET
/ SETX
comandos)
ASPNETCORE_ENVIRONMENT
Para Development
em VS para fins de depuração (ver imagem acima). E claro, quando você quiser executar seu código localmente com o ambiente de preparação, você deve definir ASPNETCORE_ENVIRONMENT
Para Staging
. E finalmente, quando você quiser executá-lo no ambiente de produção, basta remover esta variável ou definir o valor para Production
.
Para resumir: Certifica-te apenas de que o desenvolvimento , Staging ou Produção valores são usados (não 'Dev' ou qualquer outra coisa) na janela de depuração para definir o ambiente e fazer com que as diferentes extensões funcionem.
Ver também o código-fonte relevante de: ASP.NET principal:
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);
}
}
}
Se você está pensando que de onde ele leva este valor, então como este momento é estático e valor padrão é desenvolvimento.
Https://github.com/aspnet/Hosting/blob/dev/src/Microsoft.AspNet.Hosting/HostingEnvironment.cs
Quando se olha para o tipo variável IHostingEnviroment, então é Microsoft.AspNet.Hospedagem.HostingEnvrioment.
Existem duas formas de alterar agora de acordo com a configuração dinâmica.
Você pode implementar Iosting environment interface e use o seu próprio tipo para isso. Você pode ler o valor do arquivo de configuração.
-
Pode usar a interface, pode actualizar essa variável directamente aqui.
public Startup(IHostingEnvironment env) { // Setup configuration sources. Configuration = new Configuration() .AddJsonFile("config.json").AddEnvironmentVariables(); Configuration.Set("ASPNET_ENV","Your own value"); }
Se você olhar para os Serviços em serviços configuráveis, existe uma lista de serviços configuráveis por omissão e uma delas é IConfigureHostingEnviroment. A implementação por omissão é a classe interna, pelo que não poderá aceder directamente, mas poderá definir acima da chave ASPNET_ env e ler que valor.
Se precisar de definir isto sem alterar o código-a partir da linha de comandos na raiz do tipo de pasta de origem do projecto:
set ASPNET_ENV=Debug
Em VSCode Adicione o seguinte ao lançamento.json
{
"version": "0.2.0",
"configurations": [
{
...
"env": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
...
]
}
Aqui está Mais uma maneira de definir e Mudar para uma variável de ambiente em VS2017 (nota adicional à resposta de @clark-wu):
Nota: launchSettings.a json tem dois perfis no meu caso:" IISExpress "e" Project", onde o ASPNETCORE_ENVIRONMENT é definido.
{
"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/"
}
}
}
Documentação oficial: Você pode definir ASPNETCORE_AMBIENTE para qualquer valor, mas três valores são suportados pelo framework: desenvolvimento, estadiamento, e Producao. Se o ASPNETCORE_ENVIRONMENT não estiver definido, o mesmo não acontece com a produção.