是否可以在 asp.net web.config 文件中创建我自己的自定义键并使用 C# 遍历它们?你怎么做(我把 key 放在哪里?什么格式?)?我有一个 Intranet 应用程序,它根据客户端的 IP 地址执行某些操作。与其在代码隐藏文件中硬编码那些,我想我会把它们放在 web.config 中并遍历它。这样我就可以在配置文件中添加或删除,而无需重新编译所有内容。

我的 key 会有一个名字、IP 地址,也许还有其他信息。

谢谢你。

最佳答案

我认为这应该为你做...

这是在你的 web.config...

<configSections>
    <section name="DataBaseKeys" type="System.Configuration.NameValueFileSectionHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
</configSections>
<DataBaseKeys>
    <!--Connection Strings for databases (or IP Addresses or whatever)-->
    <add key="dbCon1" value="Data Source=DbServerPath;Integrated Security=True;database=DbName1"/>
    <add key="dbCon2" value="Data Source=DbServerPath;Integrated Security=True;database=DbName1"/>
    <add key="dbCon3" value="Data Source=DbServerPath;Integrated Security=True;database=DbName1"/>
    <add key="dbCon4" value="Data Source=DbServerPath;Integrated Security=True;database=DbName1"/>
    <add key="dbCon5" value="Data Source=DbServerPath;Integrated Security=True;database=DbName1"/>
</DataBaseKeys>

这是你的代码...
using System.Configuration;

using System.Collections.Specialized;

protected void Page_Load(object sender, EventArgs e)
{
    LoadDdls();
}

private void LoadDdls()
{
    NameValueCollection nvcDbKeys = GetDbKeys();

    //Loop through the collection
    for (int i = 0; i < nvcDbKeys.Count; i++)
    {
        // "Keys" is the "key" - Get(int) is the "value"
        this.DropDownList1.Items.Add(new ListItem(nvcDbKeys.Keys[i], nvcDbKeys.Get(i)));
    }
}

private NameValueCollection GetDbKeys()
{
    //Declare a name value collection to store Database Key List from web.config
    NameValueCollection nvcDatabaseKeyList;
    nvcDatabaseKeyList = (NameValueCollection) ConfigurationManager.GetSection("DataBaseKeys");

    return nvcDatabaseKeyList;
}

关于asp.net - 你如何遍历 web.config 中的自定义键?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/317591/

10-11 22:50
查看更多