【发布时间】:2019-10-09 19:17:26
【问题描述】:
我正在构建一个 ASP.NET Core 2 应用程序。我想将我的应用程序部署到 Heroku,但是,我需要从他们的环境变量 $DATABASE_URL 加载连接字符串。在我的startup.cs 我有:
namespace LearningSystems
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
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)
{
services.AddMvc().AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(20);
options.Cookie.HttpOnly = true;
});
SetupDbContext(services);
}
private void SetupDbContext(IServiceCollection services)
{
var conn = Environment.GetEnvironmentVariable("$DATABASE_URL");
var connectionString = Configuration.GetConnectionString("pmf");
services.AddEntityFrameworkNpgsql()
.AddDbContext<pmf_visualizationsContext>(options => options.UseNpgsql(connectionString));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseSession();
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "Home",
template: "",
defaults: new {controller = "Shell", action = "Index"}
);
});
}
}
}
我想在生产环境(Heroku)中加载不同的连接字符串。 但是,在SetupDbContext方法中,我不知道如何找出我所在的环境。谁能告诉我这样做的正确方法是什么?
【问题讨论】: