将参数传递给.NET Core API中的自定义类

时间:2019-08-14 06:45:44

标签: c# .net-core asp.net-core-webapi

我有一个自定义邮件类,我想将从appSettings.json中提取的电子邮件配置传递给启动类中的自定义Mail类。我该如何实现?

  public class Mail
  {        
        private IOptions<ApplicationSettings> _applicationSettings;

        public Mail(ApplicationSettings applicationSettings)
        {
            _applicationSettings = applicationSettings;

        }
   }

public class Startup
{

   services.Configure<ApplicationSettings> 
   (Configuration.GetSection("ApplicationSettings"));

}

1 个答案:

答案 0 :(得分:3)

好的,这就是我在项目中设置电子邮件配置的方式。这段代码仅供您参考,我真的希望它能对您有所帮助。

appsettings.json如下:

  "EmailConfiguration": 
  {
    "Host": "smtp.gmail.com",
    "Port": 587,
    "MailAddress": "youremailaddress@example.com",
    "MailDisplayName": "Your Display Name",
    "Username": "youremailaddress@example.com",
    "Password": "yourpassword"
  }

EmailConfiguration类基本上是用来保存配置文件中的设置的模型,看起来像这样:

public class EmailConfiguration
{
    public string Host { get; set; }
    public int Port { get; set; }
    public string MailAddress { get; set; }
    public string MailDisplayName { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
}

您将在其中声明通用interface方法的SendEmail看起来像:

public interface IEmailManager
{
   bool SendEmail<T>(string subject, string body, string fromAddress, List<string> toAddresses, List<string> ccAddresses, List<string> bccAddresses, string name = "", List<string> filePaths = null, string htmlFile = "", T data = default(T), bool apptUpdate=false);
}

最后实现上述接口的类如下:

public class EmailManager : IEmailManager
{
    private readonly EmailConfiguration _emailSettings;

    public EmailManager(EmailConfiguration emailConfiguration)
    {
        _emailSettings = emailConfiguration;
    }

    public bool SendEmail<T>(string subject, string body, string fromAddress, List<string> toAddresses, List<string> ccAddresses, List<string> bccAddresses, string name = "", List<string> filePaths = null, string htmlFile = "", T data = default(T), bool apptUpdate = false)
    {
           string host = _emailSettings.Host;
           SmtpClient smtpClient = new SmtpClient(_emailSettings.Host, _emailSettings.Port);
           smtpClient.EnableSsl = true;
           smtpClient.UseDefaultCredentials = false;
           MailAddress from = new MailAddress(_emailSettings.MailAddress, _emailSettings.MailDisplayName);
           smtpClient.Credentials = new NetworkCredential(_emailSettings.Username, _emailSettings.Password);
           MailMessage myMail = new MailMessage();
           myMail.From = from;

          //Rest logic to send email
    }    
}

确保您使用Startup.cs方法在ConfigureServices中注册该类:

var emailSettingsSection = Configuration.GetSection("EmailConfiguration");
services.Configure<EmailConfiguration>(emailSettingsSection);

此方法也可以用于您的其他配置设置。