我在 Visual Studio 2015 中创建了一个新的 ASP.NET Core Web 应用程序。我还设置了一个 Azure Web 应用程序以从 GitHub 提取该应用程序并运行它。这工作正常,但我在连接到 Azure 上的数据库时遇到问题。
在本地,这是有效的,它使用 config.json
和代码 Data:DefaultConnection:ConnectionString
作为连接字符串。
如何保留代码原样并使其在 Azure 中也能正常工作?我尝试在门户中设置应用程序设置,包括连接字符串和应用程序设置。并使用“SQLCONNSTR_DefaultConnection”和“Data:DefaultConnection:ConnectionString”作为键。
(顺便说一句,设置应用程序设置似乎不起作用。我认为我提供的值太长)。
那么,如何将 Azure 数据库的连接字符串提供给我的 Azure Web 应用程序 (ASP.NET 5),而不将其 checkin 源代码管理中?
更新 我的 Startup.cs 如下所示(请参阅 the full file on GitHub ):
public Startup(IHostingEnvironment env)
{
var configuration = new Configuration()
.AddJsonFile("config.json")
.AddJsonFile($"config.{env.EnvironmentName}.json", optional: true);
if (env.IsEnvironment("Development"))
{
configuration.AddUserSecrets();
}
configuration.AddEnvironmentVariables();
Configuration = configuration;
}
在ConfigureServices
方法中,还有:
services.Configure<AppSettings>(Configuration.GetSubKey("AppSettings"));
并且也在 ConfigureServices
方法中:
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]))
.AddDbContext<InvoicesDbContext>(options =>
options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
// So this is where I want my app in Azure to use the connection string I
// provide in the portal
最佳答案
简短回答
I've tried setting the Application Settings in the portal, both the Connection Strings and the App Settings. And using both "SQLCONNSTR_DefaultConnection" and "Data:DefaultConnection:ConnectionString" as the key.
你已经很接近了。
- 转到 Azure Web 应用 > 配置 > 连接字符串。
- 添加名为
DefaultConnection
的连接字符串。 - 使用
Configuration.Get("Data:DefaultConnection:ConnectionString")
访问它。
使用 timesheet_db
代替 DefaultConnection
的示例
这是我自己的时间表应用程序的示例。我的连接字符串名为 timesheet_db
。只需用 DefaultConnection
替换该字符串的所有实例即可使示例适应您的用例。
Azure Web 应用配置
Azure Web 应用服务控制管理器
在线服务控制经理https://myWebAppName.scm.azurewebsites.net/Env将显示连接字符串。
Startup.cs
在Startup
中设置配置设置,以便环境变量覆盖config.json。
public IConfiguration Configuration { get; set; }
public Startup()
{
Configuration = new Configuration()
.AddJsonFile("config.json")
.AddEnvironmentVariables(); <----- will cascade over config.json
}
在启动
中配置数据库。
public void ConfigureServices(IServiceCollection services)
{
services
.AddEntityFramework()
.AddSqlServer()
.AddDbContext<ProjectContext>(options =>
{
var connString =
Configuration.Get("Data:timesheet_db:ConnectionString");
options.UseSqlServer(connString);
});
}
当然,该示例使用名为 timesheet_db
的连接字符串。对于您来说,将其所有实例替换为您自己的名为 DefaultConnection
的连接字符串,一切都会正常工作。
关于c# - 在 Azure 中设置 ASP.NET Core Web 应用程序的 SQL 连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31097933/