Asp.Net VNext App Settings on Azure

前端 未结 2 848
有刺的猬
有刺的猬 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<ApplicationDbContext>(options =>
                    options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
    
            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();
    
            services.AddMvc();
    
            // Add application services.
            services.AddTransient<IEmailSender, AuthMessageSender>();
            services.AddTransient<ISmsSender, AuthMessageSender>();
    
            **services.AddInstance<IConfiguration>(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,

    0 讨论(0)
  • 2021-01-14 19:52

    If you set App Settings in the Azure Portal, they become environment variables at runtime, and should get picked up by the ASP.NET vNext runtime. So you don't need to physically modify your appsettings.json to achieve this.

    0 讨论(0)
提交回复
热议问题