在ASP.NET 5中,我们如何以编程方式访问Azure Web App的连接字符串?我已经能够检索TEST_APP_SETTINGS
值而不是TestConnString
值。
以下是我的尝试:
services.Configure<AppSettings>(Configuration.GetSubKey("AppSettings"));
我担心AppSettings
不存在。我也做了这个,应用程序设置显示但连接字符串没有显示。
Startup.cs
// Setup configuration sources.
Configuration = new Configuration()
.AddJsonFile("config.json")
.AddEnvironmentVariables();
// Allow access from *.cshtml
services.AddSingleton<Configuration>(provider =>
{
return Configuration as Configuration;
});
Dev.cshtml
@inject Microsoft.Framework.ConfigurationModel.Configuration config;
<dl>
@foreach(var k in @config.GetSubKeys())
{
<dt>@k.Key</dt>
<dd>@config.Get(k.Key)</dd>
}
</dl>
答案 0 :(得分:3)
连接字符串设置为环境变量。因此,首先必须http://cassci.datastax.com/job/cassandra-2.1_utest/lastCompletedBuild/testReport/org.apache.cassandra.io.sstable/IndexSummaryManagerTest/history/,然后连接字符串将被命名为Data:NAME:ConnectionString
,其中NAME
是门户中连接字符串的名称。
例如,如果您的连接字符串是&#34; ServerConnection&#34;然后使用Data:ServerConnection:ConnectionString
add the environment variable configuration source是验证映射环境配置映射的测试,它们可能会更好地解释它。
答案 1 :(得分:0)
这是Victor答案的延伸,帮助我了解新MVC 6环境中发生的事情。
在config.json文件中我有:
"Data": {
"DefaultConnection": {
"ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=aspnet5-TestWepApp-e35abc53-9a43-4b2b-886d-d8582c0a1ccd;Trusted_Connection=True;MultipleActiveResultSets=true"
}
},
这是我的DBContext使用空构造函数时使用的DefaultConnection。
现在,Azure连接字符串映射到Data:NAME:ConnectionString。所以我们看到了一封信。
所需要的只是命名Azure连接字符串“DefaultConnection”并确保配置中包含环境变量(默认情况下是这样),一切都按预期工作。
configuration.AddJsonFile("config.json")
// ...
configuration.AddEnvironmentVariables()
因此,当加载配置时,Data:DefaultConnection:ConnectionString的config.json值将被Azure设置的环境变量替换,因为在将config.json加载到配置中之后调用AddEnvironmentVariables。
<强>更新强>
使用OP的脚本查看Debug值后,我没有看到列出的连接字符串。
问题在于密钥是分层的。以下是应显示所有密钥的更新代码:
@*
For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
// ViewBag.Title = "Home Page";
}
@inject Microsoft.Framework.ConfigurationModel.Configuration config;
@functions{
public IEnumerable<string> GetAllKeys()
{
var keys = new List<string>();
foreach (var k in config.GetSubKeys())
{
GetAllKeys(keys, k.Key);
}
return keys;
}
public void GetAllKeys(List<string> keys, string key)
{
keys.Add(key);
foreach (var k in config.GetSubKeys(key))
{
GetAllKeys(keys, key + ":" + k.Key);
}
}
}
<dl>
@foreach (var key in GetAllKeys())
{
<dt>@key</dt>
<dd>@config.Get(key)</dd>
}
</dl>
答案 2 :(得分:0)
我发现以下方式最简单。它确实消除了将连接字符串放入源代码管理中的风险。与设置环境变量相比,我不确定它对安全性的评价。
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", true);