Storing SMTP outside the Web.Config File

2019-03-24 05:06发布

问题:

For some time now I've been storing my connection and app settings in an external file and just referencing that file via my web.config. This works really well because it allows me to keep separate connection strings and app settings. This is really handy since I find during development I will often make many changes to the webconfig and I hate having to manage the environment specific values every time I need to update my web.config.

Is there anyway I can achieve this with he SMTP configuration sections in the web.config.

回答1:

Sure, you can use the configSource attribute.

Example:

<system.net>
  <mailSettings>
   <smtp configSource="MailSettings.config"/>
  </mailSettings>
</system.net>

Then put your mailSettings configuration data in MailSettings.config

So then your MailSettings.config file would have something like:

    <network 
    host="relayServerHostname" 
    port="portNumber"
    userName="username"
    password="password" />

Update: looks like it may need to actually go in the smtp node to work properly, so I've updated the above code to indicate that - same idea, only this one should work. :)



回答2:

I'm not sure if what I have here is only for newer versions of .NET. I got a runtime error using the accepted answer.

Please update the accepted answer with the code block below if working with newer versions of .NET. The smtp node should also be in the separate file - not just the network node. The whole smtp node in the actual Web.config file is replaced by the file you put there - unlike in the appSettings where it seems to add to it.

Web.config -

  <system.net>
        <mailSettings>
          <smtp configSource="your-source-file">
          </smtp>
        </mailSettings>
    </system.net>

Your file -

   <smtp from="noreply@example.com">
      <network
        host="your-host"
        port="your-port"
        userName="your-user-name"
        password="your-password"/>
    </smtp>


回答3:

My software stores it in the registry, even in production.