从Web配置获取发送网格凭据

时间:2014-07-24 14:51:21

标签: asp.net-mvc web-config sendgrid

如何从网络配置中获取发送网格凭据

  <system.net>
    <mailSettings>
      <smtp>
        <network host="smtp.sendgrid.net" userName="username" password="password"/>
      </smtp>
    </mailSettings>
  </system.net>

而不是像这样对它们进行硬编码:

 // Init SmtpClient and send
            SmtpClient smtpClient = new SmtpClient("smtp.sendgrid.net", Convert.ToInt32(587));
            System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("username", "password");
            smtpClient.Credentials = credentials;
            smtpClient.Send(mailMsg);

1 个答案:

答案 0 :(得分:4)

一种选择是将它们存储在配置文件的<appSettings>部分中:

<configuration>
  <appSettings>
    <add key="sendGridUser" value="username" />
    <add key="sendGridPassword" value="password" />
  </appSettings>
</configuration>

然后使用ConfigurationManager类:

using System.Configuration; // May need to reference the assembly as well...don't remember

// ...

var username = ConfigurationManager.AppSettings["sendGridUser"];
var password = ConfigurationManager.AppSettings["sendGridPassword"];

注意:将密码字符串存储在SecureString而不是普通string中并不是一个坏主意,这样在完成后它就不会在内存中挂起。进一步阅读:

http://msdn.microsoft.com/en-us/library/system.security.securestring(v=vs.110).aspx