代码之家  ›  专栏  ›  技术社区  ›  German Latorre

在其他网站中使用appSettings值。配置部分

  •  0
  • German Latorre  · 技术社区  · 16 年前

    有没有一种方法可以在web中的任何其他部分使用appSettings定义的属性。配置文件?

    必须在多个部分中写入一个值(例如,电子邮件地址),并在任何发生更改的地方进行更新,这是非常不愉快的。

    2 回复  |  直到 16 年前
        1
  •  2
  •   Kobi    16 年前

    你可以用 String.Format 构建数据,并使用 {0} 在配置文件中的适当位置。
    假设你有基本的数据获取工具,这应该很容易实现。

    例如:

    <add key="Mail" value="kobi@example.com"/>
    <add key="LinkFormat" value="[[Mail Us|mailto:{0}]]"/>
    

    然后(从try/catch中剥离,检查数据):

    public static string GetEmail()
    {
        return ConfigurationManager.AppSettings["Mail"];
    }
    
    public static string GetEmailLinkformat()
    {
        string format = ConfigurationManager.AppSettings["LinkFormat"];
        string mail = GetEmail();
        return String.Format(format, mail);
    }
    
        2
  •  -1
  •   Dave Anderson    16 年前

    如果你使用 $ AppSetting值中的分隔符这些可以替换为AppSettings中的键值,例如。

    <add key="PrivacyPolicyURL" 
      value="$domain$/Default.aspx?siteid=$siteid$&amp;locid=$locid$&amp;tpid=$tpid$"
      />
    

    使用以下函数进行替换;

    public static string GetAppSetting(string key)
    {
        string keyValue = ConfigurationManager.AppSettings[key].ToString();
    
        foreach (System.Text.RegularExpressions.Match match in System.Text.RegularExpressions.Regex.Matches(keyValue, @"\$[\d\D]*?\$"))
        {
            try
            {
                string replaceWith = ConfigurationManager.AppSettings[match.Value.Replace("$", string.Empty)]  ?? string.Empty;
                keyValue = keyValue.Replace(match.Value, replaceWith);
            }
            catch
            {
                keyValue = keyValue.Replace(match.Value, string.Empty);
            }
        }
    
        return keyValue;
    }
    

    所以在这个例子中,它插入了域、siteid、locid和tpid的AppSettings,以生成如下内容:; www.mywebsite.com/Default.aspx?siteid=1001&locid=1001&tpid=1001

    推荐文章