when i publish my asp.net core web application to my local file system, it always takes the production-config and the ASPNETCORE_ENVIRONMENT variable with the value = "Production".
how and where do i have to set the value of the ASPNETCORE_ENVIRONMENT variable so that it will be considered not only for debugging, but also for the publishing? i already tried the following options without success:
This question is related to
c#
asp.net-core
environment-variables
Other than the options mentioned above, there are a couple of other Solutions.
1. Modifying the project file (.CsProj) file
MSBuild supports the EnvironmentName
Property which can help to set the right environment variable as per the Environment you wish to Deploy. The environment name would be added in the web.config during the Publish phase.
Simply open the project file (*.csProj) and add the following XML.
<!-- Custom Property Group added to add the Environment name during publish
The EnvironmentName property is used during the publish for the Environment variable in web.config
-->
<PropertyGroup Condition=" '$(Configuration)' == '' Or '$(Configuration)' == 'Debug'">
<EnvironmentName>Development</EnvironmentName>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' != '' AND '$(Configuration)' != 'Debug' ">
<EnvironmentName>Production</EnvironmentName>
</PropertyGroup>
Above code would add the environment name as Development
for Debug configuration or if no configuration is specified. For any other Configuration the Environment name would be Production
in the generated web.config file. More details here
2. Adding the EnvironmentName Property in the publish profiles.
We can add the <EnvironmentName>
property in the publish profile as well. Open the publish profile file which is located at the Properties/PublishProfiles/{profilename.pubxml}
This will set the Environment name in web.config when the project is published. More Details here
<PropertyGroup>
<EnvironmentName>Development</EnvironmentName>
</PropertyGroup>
3. Command line options using dotnet publish
Additionaly, we can pass the property EnvironmentName
as a command line option to the dotnet publish
command. Following command would include the environment variable as Development
in the web.config file.
dotnet publish -c Debug -r win-x64 /p:EnvironmentName=Development
Option1:
To set the ASPNETCORE_ENVIRONMENT environment variable in windows,
Command line - setx ASPNETCORE_ENVIRONMENT "Development"
PowerShell - $Env:ASPNETCORE_ENVIRONMENT = "Development"
For other OS refer this - https://docs.microsoft.com/en-us/aspnet/core/fundamentals/environments
Option2:
If you want to set ASPNETCORE_ENVIRONMENT using web.config
then add aspNetCore
like this-
<configuration>
<!--
Configure your application settings in appsettings.json. Learn more at http://go.microsoft.com/fwlink/?LinkId=786380
-->
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath=".\MyApplication.exe" arguments="" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false">
<environmentVariables>
<environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
</environmentVariables>
</aspNetCore>
</system.webServer>
</configuration>
You should follow the instructions provided in the documentation, using the web.config
.
<aspNetCore processPath="dotnet"
arguments=".\MyApp.dll"
stdoutLogEnabled="false"
stdoutLogFile="\\?\%home%\LogFiles\aspnetcore-stdout">
<environmentVariables>
<environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Production" />
<environmentVariable name="CONFIG_DIR" value="f:\application_config" />
</environmentVariables>
</aspNetCore>
Note that you can also set other environment variables as well.
The ASP.NET Core Module allows you specify environment variables for the process specified in the processPath attribute by specifying them in one or more environmentVariable child elements of an environmentVariables collection element under the aspNetCore element. Environment variables set in this section take precedence over system environment variables for the process.
This is how we can set it in run-time:
public class Program
{
public static void Main(string[] args)
{
Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Development");
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
Create your appsettings.*.json files. (Examples: appsettings.Development.json, appsettings.Staging.json, appsettings.Production.json)
Add your variables to those files.
Create a separate publish profile for each environment, like you normally would.
Open PublishProfiles/Development.pubxml (naming will be based on what you named the Publish Profile).
Simply add a tag to the PublishProfile to set the EnvironmentName variable, the appsettings.*.json file naming convention does the rest.
<PropertyGroup>
<EnvironmentName>Development</EnvironmentName>
</PropertyGroup>
Refer to the “Set the Environment” section.
With the latest version of dotnet cli (2.1.400 or greater), you can just set this msbuild property $(EnvironmentName)
and publish tooling will take care of adding ASPNETCORE_ENVIRONMENT to the web.config with the environment name.
Also, XDT support is available starting 2.2.100-preview1.
Sample: https://github.com/vijayrkn/webconfigtransform/blob/master/README.md
This variable can be saved in json. For example envsettings.json with content as below
{
// Possible string values reported below. When empty it use ENV variable value or
// Visual Studio setting.
// - Production
// - Staging
// - Test
// - Development
"ASPNETCORE_ENVIRONMENT": "Development"
}
Later modify your program.cs as below
public class Program
{
public static IConfiguration Configuration { get; set; }
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 environmentValue = envSettings["ASPNETCORE_ENVIRONMENT"].ToString();
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
Configuration = builder.Build();
var webHostBuilder = new WebHostBuilder()
.UseKestrel()
.CaptureStartupErrors(true)
.UseContentRoot(currentDirectoryPath)
.UseIISIntegration()
.UseStartup<Startup>();
// If none is set it use Operative System hosting enviroment
if (!string.IsNullOrWhiteSpace(environmentValue))
{
webHostBuilder.UseEnvironment(environmentValue);
}
var host = webHostBuilder.Build();
host.Run();
}
}
This way it will always be included in publish and you can change to required value according to environment where website is hosted. This method can also be used in console app as the changes are in Program.cs
I know this is an old post however thought I'd throw my simple solution into the mix since no one has suggested it.
I use the current directory to determine the current environment then flip the connection string and environment variable. This works great so long as you have a naming convention for your site folders such as test/beta/sandbox.
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var dir = Environment.CurrentDirectory;
string connectionString;
if (dir.Contains("test", StringComparison.OrdinalIgnoreCase))
{
connectionString = new ConnectionStringBuilder(server: "xxx", database: "xxx").ConnectionString;
Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Development");
}
else
{
connectionString = new ConnectionStringBuilder(server: "xxx", database: "xxx").ConnectionString;
Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Production");
}
optionsBuilder.UseSqlServer(connectionString);
optionsBuilder.UseLazyLoadingProxies();
optionsBuilder.EnableSensitiveDataLogging();
}
I found it working for me by setting this variable directly on Azure platorm (if you use it). Just select your web app -> configuration -> application settings and add the variable and its value, then press Save button.
Other option that we use in our projects in order to be able to set the environment per-site is to add a Parameters.xml file to the project with the following content:
<parameters>
<parameter name="IIS Web Application Name" defaultValue="MyApp" tags="IisApp" />
<parameter name="Environment" description="Environment" tags="">
<parameterEntry kind="XmlFile" scope="Web.config" match="/configuration/location/system.webServer/aspNetCore/environmentVariables/environmentVariable[@name='ASPNETCORE_ENVIRONMENT']/@value" />
</parameter>
</parameters>
The Build Action for this file is Content and the Copy Action is Copy If Newer so it will be part of the package to deploy.
Then, to deploy the package and set the environment, in the Release, under the "WinRM - IIS Web App Deployment" task (it works just as well when using the "IIS web app deploy" task), we set additional arguments for msdeploy:
-setParam:kind=ProviderPath,scope=contentPath,value="MySite" -setParam:name="Environment",value="Stage"
This way we can have multiple releases, all using the same artifact, but deployed as different environments.
Source: Stackoverflow.com