【发布时间】:2015-09-14 20:51:06
【问题描述】:
我在 Visual Studio 2015 中创建了一个新的 ASP.NET Core Web 应用程序。我还设置了一个 Azure Web 应用程序以从 GitHub 中拉入该应用程序并运行它。这工作正常,但我无法连接到 Azure 上的数据库。
在本地,这是可行的,它使用config.json 和代码Data:DefaultConnection:ConnectionString 作为连接字符串。
我怎样才能让代码保持原样,并让它在 Azure 中也能工作?我尝试在门户中设置应用程序设置,包括连接字符串和应用程序设置。并使用“SQLCONNSTR_DefaultConnection”和“Data:DefaultConnection:ConnectionString”作为键。
(顺便设置一下App Settings好像不行,我觉得我提供的值太长了)。
那么,如何在不将其签入源代码控制的情况下,将 Azure 数据库的连接字符串提供给我的 Azure Web 应用程序 (ASP.NET 5)?
更新 我的 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
【问题讨论】:
-
您能分享一下您的 Startup.cs 配置条目的外观吗?
-
如果您已正确设置所有内容,那么在您的 azure 网站中指定
Data:DefaultConnection:ConnectionString应该就可以了 -
您的示例代码未显示您如何访问 ConnectionString。您在哪里访问 ConnectionString?语法是什么。你也可以通过在VS中的项目属性->调试下设置环境变量来在本地测试环境变量。这有助于故障排除(即您设置 environment_variable 名称和设置名称相同)。
-
@GeraldDavis 我添加了关于如何访问连接字符串的代码。我将尝试有关项目属性的提示。
标签: c# azure asp.net-core connection-string