[英]How to access the web.config for a WCF service hosted in IIS from the code “inside” the service
正如标题所说,在重新定义我们的目标之后,我们将 2 个服务缩减为 1 个,它托管在 IIS 10.0 上,使用 BasicHttpBinding 的 Windows 2019 服务器 - 我通过反复试验发现,我之前遇到的主要问题是由所说的服务器引起的作为本地 DNS 服务的一部分。 因此,我使用普通的 IP 重新编写了与我们的数据库服务器的连接字符串。 这行得通。 为了使配置更容易,我在我的服务 web.config 的 appSettings 部分添加了一个新行
<appSettings>
<add key="Database" value="<whole connection string>"/>
我发现了微软提供的代码片段来访问 web.config - 但它似乎解析了错误的 web.config 因为我的数据丢失/整个部分在解析时似乎是空的......
我用过的代码
//Scan Thru the keys and use the Configuration Manager to make this happen
System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration(null) as System.Configuration.Configuration;
// Get the appSettings.
KeyValueConfigurationCollection appSettings = config.AppSettings.Settings;
String ret="";
foreach (string key in appSettings.AllKeys)
{
//Get your key
string tmpKey = appSettings[key].Value;
switch (key)
{
case "Database":
ret = tmpKey;
break;
}
}
然后我会使用“ret”来建立实际的连接......但到目前为止,由于上面的代码在 appSettings.AllKeys 中找不到“任何东西”(集合为空),因此对工作代码的任何提示将不胜感激。 还是 null 参数错误,尽管代码提示表明 null 指向原始 web.config
您应该能够使用访问应用程序设置
ConfigurationManager.AppSettings["Database"]
通常,您可以使用以下代码片段来获取AppSettings
部分中的值。
var result = ConfigurationManager.AppSettings["mykey"];
Console.WriteLine(result.ToString());
这是一个官方的例子和解释。
https://docs.microsoft.com/en-us/dotnet/api/system.configuration.configurationmanager.appsettings?view=netframework-4.8
https://docs.microsoft.com/en-us/dotnet/api/system.configuration.configurationmanager?view=netframework-4.8
如果有什么我可以帮忙的,请随时告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.