ASP.NET Core 6 MVC中调用web.config内SmtpSection报错的解决方法
解决ASP.NET Core 6中SmtpSection找不到的错误
直接修复编译错误
你遇到的CS0246错误是因为SmtpSection类型不在默认引用的程序集和命名空间范围内,按以下两步解决:
- 在控制器代码顶部添加命名空间引用:
using System.Net.Configuration; - 安装
System.Configuration.ConfigurationManagerNuGet包:.NET 6不再默认包含该包,可通过NuGet包管理器安装,或执行命令:dotnet add package System.Configuration.ConfigurationManager
更符合ASP.NET Core 6的配置规范
注意:ASP.NET Core中web.config主要用于IIS宿主相关配置,不推荐用来存储应用业务配置,更规范的做法是使用appsettings.json:
在
appsettings.json中添加邮件配置项:"SmtpSettings": { "From": "abc@gmail.com", "Host": "smtp.gmail.com", "Port": 587, "EnableSsl": true, "UserName": "abc@gmail.com", "Password": "jirhklutcubguuul" }创建强类型配置类(推荐,提升代码可读性和类型安全):
public class SmtpSettings { public string From { get; set; } public string Host { get; set; } public int Port { get; set; } public bool EnableSsl { get; set; } public string UserName { get; set; } public string Password { get; set; } }在
Program.cs中注册配置绑定:builder.Services.Configure<SmtpSettings>(builder.Configuration.GetSection("SmtpSettings"));在控制器中注入并使用配置:
private readonly SmtpSettings _smtpSettings; public YourController(IOptions<SmtpSettings> smtpSettings) { _smtpSettings = smtpSettings.Value; } // 发送邮件示例 public IActionResult SendTestEmail() { using var smtpClient = new SmtpClient(_smtpSettings.Host, _smtpSettings.Port) { EnableSsl = _smtpSettings.EnableSsl, Credentials = new NetworkCredential(_smtpSettings.UserName, _smtpSettings.Password) }; var mailMessage = new MailMessage( from: _smtpSettings.From, to: "target@example.com", subject: "测试邮件", body: "这是来自ASP.NET Core 6的测试邮件" ); smtpClient.Send(mailMessage); return Ok("邮件发送成功"); }
额外说明
如果坚持使用web.config的传统配置方式,除了完成前面的编译修复步骤外,需注意:ASP.NET Core仅会自动读取web.config中的appSettings和connectionStrings节点,system.net/mailSettings这类传统.NET Framework配置必须通过ConfigurationManager读取,但这种方式不符合ASP.NET Core的配置设计理念,不建议在新项目中使用。
内容的提问来源于stack exchange,提问作者Noo
相关产品推荐
相关产品推荐

