Asp.Net VNext App Settings on Azure

前端 未结 2 849
有刺的猬
有刺的猬 2021-01-14 19:05

I really enjoyed the new Configuration feature of Asp.Net vNext using de default appsettings.json

But I would like to change the values of that file when I publish t

2条回答
  •  孤街浪徒
    2021-01-14 19:49

    It worked very well David! Thank you!

    Here a sample to help our friends with the same question:

    startup.cs

    public Startup(IHostingEnvironment env)
        {
            // Set up configuration sources.
            var builder = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json")
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
    
            if (env.IsDevelopment())
            {
                // For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
                builder.AddUserSecrets();
            }
    
            **builder.AddEnvironmentVariables();**
            Configuration = builder.Build();
        }
    
    public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddEntityFramework()
                .AddSqlServer()
                .AddDbContext(options =>
                    options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
    
            services.AddIdentity()
                .AddEntityFrameworkStores()
                .AddDefaultTokenProviders();
    
            services.AddMvc();
    
            // Add application services.
            services.AddTransient();
            services.AddTransient();
    
            **services.AddInstance(Configuration);**
        }
    

    HomeController.cs

    IConfiguration _configuration;
    
        public HomeController(IConfiguration configuration)
        {
            this._configuration = configuration;
    
        }
        public IActionResult Index()
        {
    
            ViewBag.key = _configuration["Data:DefaultConnection:ConnectionString"];
            return View();
        }
    

    Index.cshtml

    @{
    ViewData["Title"] = "Home Page";
    

    } @ViewBag.key

    To see the difference, run the web app on localhost and on an azure web app changing the appsetting Data:DefaultConnection:ConnectionString

    Best,

提交回复
热议问题