简体   繁体   中英

Environment Variables in ASP.NET Core Apps

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?

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");

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM