Asp.net core .NET核心如何使用不同的环境?

Asp.net core .NET核心如何使用不同的环境?,asp.net-core,json.net,.net-core,Asp.net Core,Json.net,.net Core,我设法在web应用程序中使用不同的环境。 在开发环境中,我需要处理不同的数据库连接。 我试着在下一条道路上进行管理,但不幸的是不起作用。 appsettings.Development.json { "ConnectionStrings": { "DefaultConnection": "Server=xxx.xx.xxx.xxx;Database=dbName;User Id=xxPassword=xxxxxxx;" }, "Logging": { "Inclu

我设法在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();
}
公共IHostingEnvironment环境;
公共启动(IHostingEnvironment环境)
{
var builder=new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile(“appsettings.json”,可选:false,reloadOnChange:true)
.AddJsonFile($“appsettings.{env.EnvironmentName}.json”,可选:false)
.AddenEnvironmentVariables();
Configuration=builder.Build();
}
公共IConfiguration配置{get;}
//此方法由运行时调用。使用此方法向容器中添加服务。
public void配置服务(IServiceCollection服务)
{
if(environment.IsDevelopment())
{
services.AddDbContext(选项=>
options.UseSqlServer(Configuration.GetConnectionString(“DefaultConnection”));
}
else if(environment.IsProduction())
{
services.AddDbContext(选项=>
options.UseSqlServer(Configuration.GetConnectionString(“DefaultConnection”));
}
服务.额外性()
.AddEntityFrameworkStores()
.AddDefaultTokenProviders();
//添加应用程序服务。
services.AddTransient();
addScope(typeof(IRepository)、typeof(Repository));
services.AddTransient();
services.AddMvc();
}
我的代码在启动应用程序时出错。 启动应用程序时出错。


一般的想法是当我在开发环境中使用appsettings.development.json时,下面是解决我问题的代码

  {
  "ConnectionStrings": {
    "DefaultConnection": "Server=xxx.xx.xxx.xxx;Database=dbName;User Id=xxPassword=xxxxxxx;"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}
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..json文件

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

此代码位于startup类的构造函数中:

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}");
    }
公共启动(IHostingEnvironment环境、ILogger记录器)
{
var builder=new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile(“appsettings.json”,true,true)
.AddJsonFile($“appsettings.{env.EnvironmentName}.json”,true)
.AddenEnvironmentVariables();
Configuration=builder.Build();
_记录器=记录器;
_logger.LogInformation($“Env:{Env.EnvironmentName}”);
}
您将看到这一行:
.AddJsonFile($“appsettings.{env.EnvironmentName}.json”,true)

此设置将覆盖现有设置。 例如如果您在azure中托管应用程序,则需要使用
ASPNETCORE\u环境
test
prod
设置应用程序设置

当然,也可以在项目的“属性”选项卡上进行设置


干杯

看起来您没有将ASPNETCORE_环境变量设置为Development,而是根据需要使用配置文件$“appsettings.{env.EnvironmentName}.json”(可选:false)

若从命令行运行应用程序,则需要设置此变量

对于CMD:

set ASPNETCORE_ENVIRONMENT=Development
对于powershell:

$Env:ASPNETCORE_ENVIRONMENT = "Development"

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

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

  • 右键单击项目
  • 财产
  • 转到“调试”选项卡
  • 将“ASPNETCORE_环境”的价值更改为“开发”
应使用Rebuild和
appsettings.Development.json

或在Azure上:

  • 转到你的应用程序
  • 单击“应用程序设置”
  • 在标题“应用程序设置”下,您可以添加“ASPNETCORE_环境”

看起来您刚刚将$“appsettings.{env.EnvironmentName}.json”设置为可选,现在没有异常。您的连接字符串是否设置为正确的服务器?深入调查后,主要问题是,在public void ConfigureServices(IServiceCollection services)中,有一个始终为空的write environment.IsDevelopment()。在启动时,我制作了一个iHostingEnvironment实例,我可以在代码的其他部分使用它,该实例从环境变量中准确地获取EnvironmentName,并检入ConfiguringServices并运行正确的连接字符串。对于.net core 2.0,这一点已更改。阅读详细答案。感谢这一点-让我抓狂:公共静态IWebHostBuilder CreateWebHostBuilder(字符串[]args)=>WebHost.CreateDefaultBuilder(args).UseEnvironment(“开发”).UseStartup();