0

How can I use Environment variable in Asp.Net Core? I've already added an environment variable to my system and restarted my PC, but when I run an app and get Environment variables I don't see my variable.

Environment.GetEnvironmentVariables();

Moreover, when I add environment in code, it works fine:

Environment.SetEnvironmentVariable("my-credentials-key", my-value);

Do you have any idea how to add Environment variable and use it in ASP.NET core app?

1

2 Answers 2

2

This is how I am using Environment variables in my applications-

In Visual Studio, using launchSettings.json-

  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "MY_TEST":"123"
      }
    },
    "SamplePractice": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "MY_TEST":"123"
      }
    }
  }

Since launchSettings.json is only limited to Visual Studio, In case of publish version we use web.config-

<aspNetCore processPath="dotnet" arguments=".\MyAspNetCoreApplication.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false" >
  <environmentVariables>
    <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
    <environmentVariable name="MY_TEST" value="123" />
  </environmentVariables>
</aspNetCore>

And this environment value will read across application using -

Environment.GetEnvironmentVariable("MY_TEST");
Sign up to request clarification or add additional context in comments.

Comments

1

Briefly, in launchSettings.json file you can define environment variables for every single host. For example you can have Staging environment for IIS but development, and testing environments for Self hosting.

you can find more information in here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.