我有一个 ASP.NET Core (RC1) 应用程序,可以在本地正常运行。我遇到的问题是我的 Azure 应用程序没有拾取我的连接字符串。我问过类似的问题,但我在 this app. 中缩小了问题范围请注意,它需要 Azure 上的应用程序才能重现它。
这是我看到的问题。
首先,我的配置设置如下:
public Startup()
{
var builder = new ConfigurationBuilder()
.AddJsonFile("config.json")
.AddEnvironmentVariables();
mConfiguration = builder.Build();
}
EF7 在这里设置:
public void ConfigureServices(IServiceCollection services)
{
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<FooDbContext>(options =>
{
// I'm assuming it's failing here.
// I'm not sure how to debug it running on Azure.
// All the developer exception page shows is:
// 500 Internal Server Error "An error occurred while starting the application."
options.UseSqlServer(mConfiguration["Data:ConnectionStringTest:ConnectionString"]);
});
services.AddScoped<IFooDataService, FooSqlDataService>();
}
我的config.json
有:
{
"Data": {
"ConnectionStringTest": {
"ConnectionString": "Data Source=(localdb)\\mssqllocaldb;Initial Catalog=ConnectionStringTest"
}
}
}
这应该被我在 Azure 中设置的连接字符串覆盖:
当转到 Kudu SCM 并查看 Azure Web 应用实例上的环境变量时,我看到以下内容:
SQLAZURECONNSTR_Data:ConnectionStringTest:ConnectionString = my_connection_string_here
我假设这是在运行时使用环境变量时在幕后使用的类: EnvironmentVariablesConfigurationProvider
最佳答案
好吧,这就是我发现的,这感觉很尴尬。
您似乎需要在 Azure 中的任何地方使用 Data:{my_connection_string_key}:ConnectionString
,除了 。 This environment variable converter将构造正确的连接字符串 using this format如果连接字符串以 SQLAZURECONNSTR_
为前缀,则自动执行。
这意味着当您在 Azure 中设置连接字符串时,除了连接字符串的键之外,您需要省略所有内容。不要插入 Data:
或 :ConnectionString
...只需使用 {connection_string_key}
(引用上面的格式)即可。如果您在 Azure 键/值对中包含整个格式,EnvironmentVariablesConfigurationProvider
将在其周围添加另一个 Data:
和 :ConnectionString
,从而导致类似Data:Data:{my_connection_string_key}:ConnectionString:ConnectionString
。
在 ConfigureServices(...)
中,使用 ASP 期望的格式:
... options.UseSqlServer(mConfiguration["Data:ConnectionStringTest:ConnectionString"]);
因此,您可以在本地将其用于本地 JSON,以便在开发/后备中进行测试:
{
"Data": {
"ConnectionStringTest": {
"ConnectionString": "Data Source=(localdb)\\mssqllocaldb;Initial Catalog=ConnectionStringTest"
}
}
}
只需确保您的 Azure 连接字符串具有该格式的中间部分(使用此示例的 ConnectionStringTest
)。
这将使您在 Azure 中的环境变量的原始格式如下所示:
SQLAZURECONNSTR_ConnectionStringTest = {在此处插入连接字符串}
EnvironmentVariablesConfigurationProvider
将去掉 Azure 前缀字符串,并以硬编码格式包装您的 key :Data:{0}:ConnectionString
关于azure - 在 Azure 上运行的 Web 应用程序未拾取并使用环境变量连接字符串(ASP、NET Core RC1),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37011891/