ASP.NET核心加载连接字符串

时间:2017-12-16 11:59:06

标签: heroku asp.net-core-2.0

我正在构建一个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中,我不知道如何找出我所在的环境。谁能告诉我这是怎么回事?

1 个答案:

答案 0 :(得分:0)

您可以使用IHostingEnvironment和获取当前环境来完成此操作。

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/environments 1

[请参阅此链接以获取帮助]