【发布时间】:2010-10-04 11:25:20
【问题描述】:
如何添加和读取 web.config 文件中的值?
【问题讨论】:
标签: c# .net asp.net web-config
如何添加和读取 web.config 文件中的值?
【问题讨论】:
标签: c# .net asp.net web-config
鉴于以下 web.config:
<appSettings>
<add key="ClientId" value="127605460617602"/>
<add key="RedirectUrl" value="http://localhost:49548/Redirect.aspx"/>
</appSettings>
示例用法:
using System.Configuration;
string clientId = ConfigurationManager.AppSettings["ClientId"];
string redirectUrl = ConfigurationManager.AppSettings["RedirectUrl"];
【讨论】:
ToString,因为 AppSettings 上的索引器返回类型为 string 本身的值
我建议你不要修改你的web.config,因为每次更改时,它都会重新启动你的应用程序。
但是您可以使用System.Configuration.ConfigurationManager.AppSettings 阅读 web.config
【讨论】:
如果您需要基础知识,可以通过以下方式访问密钥:
string myKey = System.Configuration.ConfigurationManager.AppSettings["myKey"].ToString();
string imageFolder = System.Configuration.ConfigurationManager.AppSettings["imageFolder"].ToString();
为了访问我的网络配置键,我总是在我的应用程序中创建一个静态类。这意味着我可以在任何需要的地方访问它们,并且我没有在我的应用程序中使用字符串(如果它在 web 配置中发生更改,我必须经历所有更改它们的事件)。这是一个示例:
using System.Configuration;
public static class AppSettingsGet
{
public static string myKey
{
get { return ConfigurationManager.AppSettings["myKey"].ToString(); }
}
public static string imageFolder
{
get { return ConfigurationManager.AppSettings["imageFolder"].ToString(); }
}
// I also get my connection string from here
public static string ConnectionString
{
get { return ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; }
}
}
【讨论】:
假设密钥包含在<appSettings> 节点内:
ConfigurationSettings.AppSettings["theKey"];
至于“写作”——简单地说,不要。
web.config 不是为此而设计的,如果您要不断更改值,请将其放入静态帮助程序类中。
【讨论】:
Ryan Farley 在他的博客中有一篇很棒的文章,包括为什么不写回 web.config 文件的所有原因: Writing to Your .NET Application's Config File
【讨论】:
我是 siteConfiguration 类,用于以这种方式调用我的所有 appSetting。如果它对任何人有帮助,我会分享它。
在“web.config”中添加以下代码
<configuration>
<configSections>
<!-- some stuff omitted here -->
</configSections>
<appSettings>
<add key="appKeyString" value="abc" />
<add key="appKeyInt" value="123" />
</appSettings>
</configuration>
现在您可以定义一个类来获取所有 appSetting 值。像这样
using System;
using System.Configuration;
namespace Configuration
{
public static class SiteConfigurationReader
{
public static String appKeyString //for string type value
{
get
{
return ConfigurationManager.AppSettings.Get("appKeyString");
}
}
public static Int32 appKeyInt //to get integer value
{
get
{
return ConfigurationManager.AppSettings.Get("appKeyInt").ToInteger(true);
}
}
// you can also get the app setting by passing the key
public static Int32 GetAppSettingsInteger(string keyName)
{
try
{
return Convert.ToInt32(ConfigurationManager.AppSettings.Get(keyName));
}
catch
{
return 0;
}
}
}
}
现在添加上一个类的引用并访问如下所示的关键调用
string appKeyStringVal= SiteConfigurationReader.appKeyString;
int appKeyIntVal= SiteConfigurationReader.appKeyInt;
int appKeyStringByPassingKey = SiteConfigurationReader.GetAppSettingsInteger("appKeyInt");
【讨论】: