从ASP.NET Core 1 RC1 IConfiguration访问环境变量 [英] Accessing environment variables from ASP.NET Core 1 RC1 IConfiguration

查看:146
本文介绍了从ASP.NET Core 1 RC1 IConfiguration访问环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究如何正确处理环境变量以及在多个环境中配置我的应用程序.我选择从Development中的 config.json 中读取,并在Production中使用环境变量.

I am working on learning how to properly handle environment variables and configuring my app in multiple environments. I've chosen to read from a config.json in Development, and use environment variables in Production.

我有以下 Startup.cs 来演示这一点:

I have the following Startup.cs to demonstrate this:

using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http;
using Microsoft.Extensions.Configuration;

namespace Variables
{
    public class Startup
    {
        private IConfiguration mConfiguration;

        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder();
            if (env.IsDevelopment())
            {
                // Only load from config when in development.
                builder.AddJsonFile("config.json");
            }
            builder.AddEnvironmentVariables();
            mConfiguration = builder.Build();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseIISPlatformHandler();
            app.UseDeveloperExceptionPage();

            app.Run(async (context) =>
            {
                // Succeeds with hosting:environment=Development, fails with hosting:environment=Production
                // ArgumentNullException: Value cannot be null. Parameter name: text
                //  Environment variable setup in Windows with:
                //  set bar=1
                await context.Response.WriteAsync(mConfiguration["bar"]);
            });
        }

        public static void Main(string[] args) => WebApplication.Run<Startup>(args);
    }
}

我的 config.json 很简单:

{
  "bar": 1
}

hosting:environment=Development运行时,此操作成功.但是,当以hosting:environment=Production身份运行时,这将失败.我在Windows中使用set bar=1设置了环境变量.

This succeeds when running as hosting:environment=Development. This fails though, when running as hosting:environment=Production. I set up an environment variable in Windows with set bar=1.

我也尝试利用系统环境变量(因为我不确定是否打开命令提示符并键入set bar=1是否会导致用户环境变量或系统变量),但是在失败时会出现相同的错误同时运行我的应用.

I've also tried utilizing the system environment variables (because I'm not sure if opening up a command prompt and typing set bar=1 does a user environment variable, or system variable), but it fails with the same error when running my app as well.

推荐答案

在我的机器上工作

config.json具有{ "bar": 1 }并使用此代码...

Works on My Machine

With config.json having { "bar": 1 } and using this code...

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder();
    if (env.IsDevelopment())
    {
        builder.AddJsonFile("config.json");
    }

    builder.AddEnvironmentVariables();
    mConfiguration = builder.Build();
}

public IConfigurationRoot mConfiguration { get; set; }

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.Run(async (context) =>
    {
        await context.Response.WriteAsync(env.EnvironmentName);
        await context.Response.WriteAsync($"\r\n");

        await context.Response.WriteAsync(mConfiguration["bar"]);
        await context.Response.WriteAsync($"\r\n");
    });
}

    public static void Main(string[] args) => 
        Microsoft.AspNet.Hosting.WebApplication.Run<Startup>(args);
}

...运行以下命令...

...running the following commands...

CMD> dnvm use 1.0.0-rc1-update2
CMD> set bar=3
CMD> dnx web

...将其显示在网络浏览器中.

...displays this in the web browser.

如果使用的是Visual Studio,请在更改环境变量后重新启动它.或者,通过Visual Studio定义环境变量,这样就不必重新启动.

If you're using Visual Studio, restart it after you have changed an environmental variable. Alternatively, define the environmental variable through Visual Studio, so that you do not have to restart.

  1. 右键单击项目">属性"
  2. 调试
  3. 环境变量
  4. 添加
  5. 全部保存

重新启动外壳. dnx web仅选择其外壳中可用的环境变量.如果您在其他位置定义了环境变量之后打开了外壳程序,那么您将需要重新启动外壳程序.

Restart your shell. dnx web only picks up environmental variables that are available in its shell. If you opened the shell after defining the environmental variable elsewhere, then you will need to restart your shell.

检查您的外壳程序(PowerShell,命令提示符或bash)是否知道环境变量:

Check that your shell (PowerShell, command prompt, or bash) is aware of the environmental variable:

PS> $env:bar          
CMD> SET bar          
$ printenv bar      

如果您的外壳不知道环境变量,请按以下步骤进行设置:

If your shell is not aware of the environmental variable, set it like this:

PS> $env:bar = 3
CMD> SET bar=3
$ export bar=3

两者

转储您的应用程序知道的所有环境变量:

Both

Dump all the environmental variables about which your app is aware:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.Run(async (context) =>
    {
        foreach (var envVar in mConfiguration.GetChildren())
        {
            await context.Response.WriteAsync($"{envVar.Key}: {envVar.Value}");
            await context.Response.WriteAsync($"\r\n");
        }
    });
}

检查您的应用程序是否已在生产环境中运行:

Check that your app is running in production:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.Run(async (context) =>
    {
        await context.Response.WriteAsync(env.EnvironmentName);
        await context.Response.WriteAsync($"\r\n");
    });
}

这篇关于从ASP.NET Core 1 RC1 IConfiguration访问环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆