Reputation: 545
In Configure
method in Startup
class of ASP.NET Core WebAPI project
...
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
injected IWebHostEnvironment
is driven by the value in the ASPNETCORE_ENVIRONMENT environment variable.
Can we rename this variable? If yes, Is it a good practice to rename it?
Upvotes: 3
Views: 1186
Reputation: 4376
There is a built in way to set the environment for the application:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseEnvironment("WHAT EVER YOU WANT")//set it for this app
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
As you can see you can use 'UseEnvironment("MY COOL ENVIRONMENT")' to set it to what ever you want.
And the source of it can be any environment variable, file, database, hard coded... any thing you can think of.
Here is some documentation. Scroll to the section called EnvironmentName to find information about it.
Upvotes: 1
Reputation: 388303
You cannot really rename the names of the environment variables ASPNETCORE_ENVIRONMENT
or DOTNET_ENVIRONMENT
. Those are built into the default host builder that you will likely use when creating ASP.NET Core applications.
What you can do however is configure the host with your own configuration sources. That way, you can inject configurations from environment variables that do not follow standard names. For example, if you wanted to read the environment name from the environment variable stage
, then you could modify the CreateHostBuilder
to include a call to ConfigureHostConfiguration
that modifies the configuration:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureHostConfiguration(c => {
c.AddInMemoryCollection(new Dictionary<string, string>()
{
["Environment"] = Environment.GetEnvironmentVariable("stage"),
});
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
Note that if you call ConfigureHostConfiguration
before ConfigureWebHostDefaults
, then you will need to make sure that your launchSettings.json
does not contain a configuration for the ASPNETCORE_ENVIRONMENT
variable or your custom variable will be overwritten. You can also swap those two calls around to make your environment variable take precedence over the standard name. Of course this only applies in development (since there is no launchSettings.json
in production).
To answer your final question: Is this a good idea? Probably not. Unless you need to do this for external reasons (e.g. to fit into existing deployment processes you don’t have control over), you should stick to the default names to make sure that all involved parties understand the impact properly.
And just to clarify this: Both DOTNET_ENVIRONMENT
and ASPNETCORE_ENVIRONMENT
are good to use and the latter is not going away any time soon.
Upvotes: 3