Matthew Layton
Matthew Layton

Reputation: 42380

How does IHostingEnvironment.EnvironmentName work?

In a .NET Core console application, if I add the following line...

IHostingEnvironment env = new HostingEnvironment();
Console.WriteLine(env.EnvironmentName);

I get this result...

Production

But when I do the same thing in an ASP.NET Core application on the same machine...

public Startup(IHostingEnvironment env)
{
    Debug.WriteLine(env.EnvironmentName);
}

I get this result...

Development


As an extra point, can EnvironmentName be configured to work with Debug and Release configurations within the solution?

enter image description here

The ultimate goal is to be able to connect to a local SQL database when built using Debug, and an Azure database when built using Release.

Upvotes: 9

Views: 4351

Answers (1)

Shaun Luttin
Shaun Luttin

Reputation: 141672

How exactly does EnvironmentName work?

.NET Core reads the name from an environmental variable.

How can I specify that my local machine is a Development environment?

Set the environmental variable to Development.

How can I specify that Azure is a Production environment?

Set the environmental variable to Production.

As an extra point, can EnvironmentName be configured to work with Debug and Release configurations within the solution?

You can create a launch profile that sets the environment name and use that profile with either Debug or Release configuration. The launch profile impacts the EnvironmentName when you launch from Visual Studio; you will need to use other means to set it, when you run the app in other environments.

The image below shows running the application in Release configuration and a MyDevProfile that sets EnvironmentName to Development.

enter image description here

Upvotes: 10

Related Questions