asp.net-mvc – 与SmtpClient.UseDefaultCredentials属性混淆

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 与SmtpClient.UseDefaultCredentials属性混淆前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在我的MVC4应用程序中,我使用SmtpClient通过Gmail的smtp.gmail.com SMTP服务器发送电子邮件.

我已经使用以下设置配置了我的Web.Config文件

<system.net>
 <mailSettings>
  <smtp deliveryMethod="Network">
   <network enableSsl="true" 
   defaultCredentials="false" 
   host="smtp.gmail.com" 
   port="587" 
   userName="xxMyUserNamexx@gmail.com" 
   password="xxMyPasswordxx" />
  </smtp>
 </mailSettings>
</system.net>

使用SmtpClient并发送电子邮件方法如下所示:

public void SendMail(string fromDisplayName,string fromEmailAddress,string toEmailAddress,string subject,string body)
{
    MailAddress from = new MailAddress(fromEmailAddress,fromDisplayName);
    MailAddress to = new MailAddress(toEmailAddress);
    MailMessage mailMessage = new MailMessage(from,to);
    mailMessage.Body = body;
    mailMessage.Subject = subject;

    SmtpClient client = new SmtpClient();
    //client.UseDefaultCredentials = false;
    client.Send(mailMessage);
}

以上代码按预期工作正常.有什么困扰我的是注释行client.UseDefaultCredentials = false; – 如果我要取消对该行的注释,我将收到一条异常消息,其中指出:

The SMTP server requires a secure connection or the client was not
authenticated. The server response was: 5.5.1 Authentication required.

更重要的是,如果我将UseDefaultCredentials属性设置为true或false,我仍然会收到异常消息.避免异常消息的唯一方法是完全删除该行.

这个行为是否正常?你能解释为什么我收到异常消息吗?

解决方法

So why would me explicitly setting the property to false throw an exception?

原因是因为UseDefaultCredentials的setter将Credentials属性设置为null,如果将其设置为false,或者将其设置为CredentialCache.DefaultNetworkCredentials属性(如果设置为true). DefaultNetworkCredentials属性defined by MSDN as

The credentials returned by DefaultNetworkCredentials represents the authentication credentials for the current security context in which the application is running. For a client-side application,these are usually the Windows credentials (user name,password,and domain) of the user running the application. For ASP.NET applications,the default network credentials are the user credentials of the logged-in user,or the user being impersonated.

当您将UseDefaultCredentials设置为true时,它将使用您的IIS用户,并且假设您的IIS用户与您使用的任何SMTP服务器的帐户不具有与您的帐户相同的身份验证凭据.将UseDefaultCredentials设置为false将设置的凭据设置为false.所以无论哪种方式你都会得到这个错误.

以下是使用dotPeek的UseDefaultCredentials设置器:

set
{
    if (this.InCall)
    {
        throw new InvalidOperationException(
            SR.GetString("SmtpInvalidOperationDuringSend"));
    }
    this.transport.Credentials = value 
        ? (ICredentialsByHost) CredentialCache.DefaultNetworkCredentials 
        : (ICredentialsByHost) null;
  }

猜你在找的asp.Net相关文章