我的程序无法读取app.config文件中的键,如下所示:
<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" />
<add key="webpages: Version" value="2.0.0.0" />
<add key="webpages:Enabled" value="false" />
<!--Email settings-->
<add key="TOADDRESS" value="myMail@host.com" />
<add key="PASSWORD" value="password" />
<add key="SMTPHOST" value="asmtp.host.com" />
<add key="SMTPPORT" value="587" />
<!--End email settings-->
</appSettings>
这是用来读取App.Config的C#代码:
public PartialViewResult SendMail(EmailModel model)
{
string host = ConfigurationManager.AppSettings.Get("SMTPHOST");
int port = Convert.ToInt16(ConfigurationManager.AppSettings.Get("SMTPPORT"));
string receiver = ConfigurationManager.AppSettings.Get("TOADDRESS");
string password = ConfigurationManager.AppSettings.Get("PASSWORD");
SmtpClient smtp = new SmtpClient(host, port);
smtp.Credentials = new NetworkCredential(receiver, password);
smtp.EnableSsl = true;
MailMessage mailMsg = null;
try
{
mailMsg = new MailMessage(model.from, receiver, model.subject, model.body);
smtp.Send(mailMsg);
}
catch (Exception ex)
{
SendErrorMail();
}
return PartialView("_About");
}
我也试过使用大括号,如:string host = ConfigurationManager.AppSettings["SMTPHOST"];
,但这也不起作用。
但是,如果我对C#代码中的值进行硬编码,而不使用App.Config,则可以正常工作。
我做错了什么?
我收到一条错误消息,指出找不到smtp主机。如果我手动输入smtphost,我会在其他值上获得异常,作为TOADDRESS
等的空引用。我将获得App.Config中所有值/键的空引用