【问题标题】:ASP.NET core load connection stringASP.NET 核心加载连接字符串
【发布时间】: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方法中,我不知道如何找出我所在的环境。谁能告诉我这样做的正确方法是什么?

【问题讨论】:

    标签: heroku asp.net-core-2.0


    【解决方案1】:

    您可以通过使用 IHostingEnvironment 和获取当前环境来做到这一点。

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

    [请参考此链接寻求帮助]

    【讨论】:

      猜你喜欢
      • 2019-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-02
      • 1970-01-01
      • 2019-03-10
      • 2018-02-21
      • 1970-01-01
      相关资源
      最近更新 更多