Updated on Kisan Patel
Problem:
How to Configure ConnectionString in ASP.NET vNext?
How to configure connection string in MVC 6 in ASP.NET vNext?
Solution:
Open config.json
. Add the following highlighted lines:
{ "AppSettings": { "SiteTitle": "HelloWorld" }, "Data": { "DefaultConnection": { "ConnectionString": "Data Source=ADMIN-PC\\SQLEXPRESS;Initial Catalog=Hello;User ID=sa;Password=sa123;" } } }
This defines a connection string to SQL Server Database, which is a lightweight express version of SQL Server Express for development.
Open the Startup.cs
file. In the ConfigureServices
method, add:
public void ConfigureServices(IServiceCollection services) { // Add Entity Framework services to the services container. services.AddEntityFramework() .AddSqlServer() .AddDbContext(options => options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"])); // Add MVC services to the services container. services.AddMvc(); }
Notice in ConfigureServices that we call Configuration.Get to get the database connection string. During development, this setting comes from the config.json file.
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv) { // Setup configuration sources. var builder = new ConfigurationBuilder(appEnv.ApplicationBasePath) .AddJsonFile("config.json") .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfiguration Configuration { get; set; }
When you deploy the app to a production environment, you set the connection string in an environment variable on the host. If the Configuration API finds an environment variable with the same key, it returns the environment variable instead of the value that is in config.json.
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv) { // Setup configuration sources. var builder = new ConfigurationBuilder(appEnv.ApplicationBasePath) .AddJsonFile("config.json") .AddJsonFile($"config.{env.EnvironmentName}.json", optional: true); if (env.IsDevelopment()) { // This reads the configuration keys from the secret store. // 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 IConfiguration Configuration { get; set; }