有没有办法使用类似字典的集合作为应用程序设置对象?

时间:2009-06-08 19:48:38

标签: asp.net vb.net dictionary

我想在ASP.NET Web应用程序的应用程序设置中存储一组键/值对,但我找不到直接的方法。例如,这些two questions告诉我StringDictionary等不会序列化为XML,并建议我必须推出自己的实现。但似乎这应该更容易做到;毕竟,web.config是XML和<的applicationSettings>本质上是键/值对的集合,所以感觉我错过了一些明显的东西。鉴于我下面的具体情况,我是否真的必须推出自己的序列化,还是有更简单的解决方法?

有问题的网络应用是一个基本的联系表单,它根据参数的值向不同的收件人发送电子邮件;例如http://www.examplesite.com/Contact.aspx?recipient=support会向SupportGroup@exampledomain.com发送电子邮件。

目标是通过编辑web.config文件来添加或删除收件人(或更改其地址),这样我就不必重新编译,并且可以在测试和生产环境中轻松维护不同的配置。例如:

// I can use something like this for the sender address
SmtpMsg.From = New MailAddress(My.Settings.EmailSender)

// And then just edit this part of web.config to use 
// different addresses in different environments.
<setting name="EmailSender" serializeAs="String">
 <value>webcontact@exampledomain.com</value>
</setting>

// I want something like this for the recipients
SmtpMsg.To.Add(My.Settings.Recipients("support"))

// and presumably some sort of equivalent xml in web.config
// maybe something like this???
<recipients>
  <item name="support" serializeAs="String">
   <value>SupportGroup@exampledomain.com</value>
  </item>
  <!-- add or remove item elements here -->
</recipients>

编辑:因为代码着色

而取代了带有C#注释的VB注释

2 个答案:

答案 0 :(得分:5)

简单的方法显然是将它们放在应用程序设置中,但它不会很整洁:

<appSettings>
  <add key="EmailSupport" value="support@somedomain.com" />
  <add key="EmailSales" value="sales@somedomain.com" />
</appSettings>

然后在您的代码中,您只需执行以下操作:

if (!string.IsNullOrEmpty(Request["recipient"])) {
  string recipientEmail = 
         WebConfigurationManager.AppSettings["Email" + Request["recipient"]];
  // Send your email to recipientEmail
}

如果你想要有点整洁,你可以像这样创建一个自定义的Configuration Section(C#我很害怕,但the docs have VB也是如此):

namespace EmailSystem {
  public class EmailRecipientsSection : ConfigurationSection {
    [ConfigurationProperty("emailSender", IsRequired = true, IsKey = false)]
    public string EmailSender {
        get { return (string)this["name"]; }
        set { this["name"] = value; }
    }

    [ConfigurationProperty("emailRecipients", IsDefaultCollection = true)]
    public EmailRecipientCollection EmailRecipients {
      get {
        var emailRecipientCollection = 
              (EmailRecipientCollection) base["emailRecipients"];
        return emailRecipientCollection;
      }
    }
  }

  public class EmailRecipientCollection : ConfigurationElementCollection {
    public EmailRecipientElement this[int index] {
      get { return (EmailRecipientElement) BaseGet(index); }
      set {
        if (BaseGet(index) != null) {
          BaseRemoveAt(index);
        }
        BaseAdd(index, value);
      }
    }

    public new EmailRecipientElement this[string name] {
      get { return (EmailRecipientElement) BaseGet(name); }
    }

    protected override ConfigurationElement CreateNewElement() {
      return new EmailRecipientElement();
    }

    protected override object GetElementKey(ConfigurationElement element) {
      return ((EmailRecipientElement) element).Name;
    }
  }

  public class EmailRecipientElement : ConfigurationElement {
    [ConfigurationProperty("name", IsRequired = true, IsKey = true)]
    public string Name {
      get { return (string) this["name"]; }
      set { this["name"] = value; }
    }

    [ConfigurationProperty("emailAddress", IsRequired = true)]
    public string EmailAddress {
      get { return (string) this["emailAddress"]; }
      set { this["emailAddress"] = value; }
    }
  }
}

然后在你的web.config中有这样的东西:

<configSections>
  [...]
  <section name="EmailSystem" type="EmailSystem, AssmeblyName" />
</configSections>

<EmailSystem emailSender="fromAddress@somedomain.com">
  <emailRecipients>
    <clear />
    <add name="Support" emailAddress="support@somedomain.com" />
    <add name="Sales" emailAddress="sales@somedomain.com" />
  </emailRecipients>
</EmailSystem>

然后你可以调用它:

emailRecipient = Request["recipient"];

var emailSystem = ConfigurationManager.GetSection("EmailSystem")
                    as EmailRecipientsSection;

string recipientEmail = emailSystem.EmailRecipients[emailRecipient].emailAddress;

// send email to recipientEmail.

答案 1 :(得分:3)

你可以做几件事,但老实说我认为这是最简单的:

<appSettings>
    <add key="testValues" value="someone@abc.com, someoneElse@abc.com, yetAnotherSomeone@abc.com" />
</appSettings>

然后你可以通过以下方式获取你的对象:

String[] temp =
ConfigurationManager.AppSettings.GetValues("testValues").ToString().Split(',');

然后执行一个简单的foreach语句来检索。您可以甚至将其设置为要缓存的静态对象,以便更快地检索。 :)

希望这有帮助,

JP

编辑:另一种情况涉及:

<appSettings file="test.config">
<!-- other settings to default to if test.config doesn't exist -->
</appSettings>

在这种情况下,如果测试环境中存在test.config文件,则将对该文件进行AppSettings.GetValues()调用。如果test.config文件不存在,ConfigurationManager类将使用web.config文件中appSettings节点中的值。