【发布时间】:2019-07-17 23:16:45
【问题描述】:
我想问有没有办法告诉 ASP.NET Core 2 选择不同的连接字符串。
每次我将我的网站发布到托管服务器时,不断更改appsettings.json 文件中的连接字符串非常烦人..
我正在使用此代码来获取连接字符串。
services.AddDbContext<AppIdentityDbContext>(options =>
options.UseSqlServer(Configuration["Data:WebDataBase:ConnectionString"]));
也许有一种简单的方法,但我正在考虑在我的 Startup.cs 中使用 if 语句:
if (local) {
services.AddDbContext<AppIdentityDbContext>(options =>
options.UseSqlServer(Configuration["Data:WebDataBase1:ConnectionString"]));
}
else {
services.AddDbContext<AppIdentityDbContext>(options =>
options.UseSqlServer(Configuration["Data:WebDataBase2:ConnectionString"]));
}
但是,无论服务器是我的本地计算机还是实时托管服务器,我如何设置这个 local 变量?
"Data": {
"WebDataBase1": {
"ConnectionString": "Data Source=DatasoruceName;Initial Catalog=DBname;Trusted_Connection=True;Integrated Security=True;"
},
"WebDataBase2": {
"ConnectionString": "Data Source=DatasoruceName;Initial Catalog=DatabaseName;Trusted_Connection=True;Integrated Security=True;"
}
}
【问题讨论】:
-
您似乎正在尝试分离环境。这是可用的方法之一:docs.microsoft.com/en-us/aspnet/core/fundamentals/…
-
另外,如果你想保护你的连接字符串,也可以看看这里:docs.microsoft.com/en-us/aspnet/core/security/…
-
完全是 Baranyi,我在想也许我应该在我的 ConfigureServices 中使用 IHostingEnvironment env 并检查 env.IsDevelopment() 与否......但我不确定这会起作用还是有更好的
-
它不起作用... ConfigureServices 方法必须是无参数的,或者只接受一个 IServiceCollection 类型的参数。
标签: c# .net asp.net-core asp.net-core-2.0 asp.net-core-configuration