【问题标题】:.NET Core How use different Environment?.NET Core 如何使用不同的环境?
【发布时间】:2017-10-11 11:53:42
【问题描述】:

我设法在 Web 应用程序中拥有不同的环境。 在开发环境中,我需要处理不同的数据库连接。 我试图管理下一条路,但不幸的是不起作用。 appsettings.Development.json

  {
  "ConnectionStrings": {
    "DefaultConnection": "Server=xxx.xx.xxx.xxx;Database=dbName;User Id=xxPassword=xxxxxxx;"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}

appsettings.json

 {
  "ConnectionStrings": {
    "DefaultConnection": "Server=xxx.xx.xxx.xxx;Database=dbName;User Id=xxPassword=xxxxxxx;"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}

Startup.cs

public IHostingEnvironment environment;

public Startup(IHostingEnvironment env)
{

    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: false)
        .AddEnvironmentVariables();
    Configuration = builder.Build();
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    if (environment.IsDevelopment())
    {
        services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    }
    else if (environment.IsProduction())
    {
        services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    }


    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();

    // Add application services.
    services.AddTransient<IEmailSender, EmailSender>();
    services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
    services.AddTransient<DbInitializer>();


    services.AddMvc();
}

使用我的代码启动应用程序时出现错误。 启动应用程序时出错。

一般的想法是当我在开发环境中使用 appsettings.Development.json

【问题讨论】:

    标签: asp.net-core json.net .net-core


    【解决方案1】:

    您需要设置变量。然后创建额外的 appsettings..json 文件。

    所以你可能已经有了 appsettings.json 我们通常还会创建一个 appsettings.test.json 和一个 appsettings.prod.json。

    在启动类中使用此代码,在构造函数中:

    public Startup(IHostingEnvironment env, ILogger<Startup> logger)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", true, true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", true)
                .AddEnvironmentVariables();
    
            Configuration = builder.Build();
    
            _logger = logger;
    
            _logger.LogInformation($"Env: {env.EnvironmentName}");
        }
    

    你看到这条线:.AddJsonFile($"appsettings.{env.EnvironmentName}.json", true)

    这一项将覆盖现有设置。 例如;如果您在 azure 中托管您的应用程序,您需要使用 ASPNETCORE_ENVIRONMENTtestprod.. 设置应用程序设置。

    当然你也可以在项目的属性选项卡上设置它

    干杯!

    【讨论】:

    • 对于 .net core 2.0 这已经改变了。阅读joonasw.net/view/aspnet-core-2-configuration-changes了解详细答案。
    • 谢谢你 - 快把我逼疯了:public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseEnvironment("Development") .UseStartup();
    【解决方案2】:

    看起来您没有将 ASPNETCORE_ENVIRONMENT 变量设置为 Development 并根据需要使用配置文件 $"appsettings.{env.EnvironmentName}.json" (可选:false)

    如果您从命令行运行应用程序,则需要设置此变量。

    对于 CMD:

    set ASPNETCORE_ENVIRONMENT=Development
    

    对于 powershell:

    $Env:ASPNETCORE_ENVIRONMENT = "Development"
    

    如果您从 Visual Studio 运行项目,您可以在项目属性的“调试”选项卡上设置此变量。您只需要使用 UI 添加此环境变量。

    【讨论】:

      【解决方案3】:

      这是解决我的问题的代码。

      private IHostingEnvironment _env;
      
              public Startup(IHostingEnvironment env)
              {
                  _env = env;
      
      
                  var builder = new ConfigurationBuilder()
                      .SetBasePath(env.ContentRootPath)
                      .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                      .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                      .AddEnvironmentVariables();
                  Configuration = builder.Build();
      
              }
      

      【讨论】:

      • 看起来您只是将 $"appsettings.{env.EnvironmentName}.json" 设置为可选,现在您没有例外。您的连接字符串是否设置为正确的服务器?
      • 经过深入调查,主要问题是,在 public void ConfigureServices(IServiceCollection services) 中写入了始终为空的 enviroment.IsDevelopment()。与在 Startup 中相比,我创建了一个 IHostingEnviroment 实例,我可以在代码的其他部分使用它,该实例从环境变量中准确获取环境名称,并检查正在配置服务并运行正确的连接字符串。
      【解决方案4】:

      据我所知,EnvironmentName 是在项目的“环境变量”中设置的。

      • 右键单击项目。
      • 属性。
      • 转到“调试”选项卡。
      • 将“ASPNETCORE_ENVIRONMENT”的值更改为“开发”。

      应该使用重建和appsettings.Development.json

      或者在 Azure 上:

      • 转到您的应用
      • 点击“应用程序设置”
      • 您可以在“应用设置”标题下添加“ASPNETCORE_ENVIRONMENT”

      【讨论】:

        猜你喜欢
        • 2018-07-04
        • 1970-01-01
        • 2021-04-07
        • 2011-01-15
        • 2019-04-30
        • 2018-01-01
        • 2020-04-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多