从SendAsync方法中的Web.Config获取邮件设置?

时间:2017-12-01 11:33:46

标签: asp.net-mvc email forgot-password sendasync

我正在使用忘记密码功能。在我的web.config文件中,我完成了邮件设置:

<system.net>
    <mailSettings>
      <smtp from="email">
        <network host="host" port="25" userName="" password="=" enableSsl="true" />
      </smtp>
    </mailSettings>
</system.net>

在我的SendAsync方法中,我尝试从web.config读取设置:

SmtpClient client = new SmtpClient();
return client.SendMailAsync(ConfigurationManager.AppSettings["SupportEmailAddr"],
                                    message.Destination,
                                    message.Subject,
                                    message.Body);

我不知道这是什么:AppSettings["SupportEmailAddr"]

我是从here获取的。

它给了我以下例外:

  

值不能为空。参数名称:来自

1 个答案:

答案 0 :(得分:1)

在您的web.config文件中,您有一个名为<appSettings>的部分。

这也是ConfigurationManager.AppSettings所指的。

["SupportEmailAddr"]正在查看名为SupportEmailAddr的具体设置。

在你的web.config中,它看起来像这样:

<appSettings>
    <add key="SupportEmailAddr" value="someone@example.com" />
</appSettings>

您获取的值不能为空消息,因为您不会像上面那样在web.config中进行设置。

因此,要修复错误消息,请找到您的<appSettings>并添加:

<add key="SupportEmailAddr" value="someone@example.com" />

或者,如果您已经在AppSettings中拥有当前值,那么只需在C#代码中更改您要查找的密钥。

ConfigurationManager.AppSettings["CorrectAppSettingKey"]

注意:如果您计划使用任何web.config继承功能,则应WebConfiguratonManger.AppSettings而不是ConfigurationManager.AppSettings。请在此处查看两者之间的差异:What's the difference between the WebConfigurationManager and the ConfigurationManager?