我目前正在设置一个 .net 核心 Web 应用程序,并设置了 MailKit 来处理它的电子邮件发送。
我没有硬编码我的 smtp 密码,而是使用了用户密码选项。但是由于某种原因,每次我尝试检索密码时,它都会返回为空。错误:
处理请求时发生未处理的异常。ArgumentNullException:值不能为空。参数名称:MessageServices.cs 中的密码 MoveNext,第 56 行
我想知道是否有人能看到我缺少的东西!
这是我的 MessageService.cs
public class AuthMessageSender : IEmailSender, ISmsSender
{
public IConfiguration Configuration { get; set; }
public AuthMessageSender()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
Configuration = builder.Build();
}
public async Task SendEmailAsync(string email, string subject, string message, string fullName)
{
try
{
var _email = "info@*******.co.uk";
var _epass = Configuration["AdminPassword:Email"];
var _dispName = "Mark ****";
var myMessage = new MimeMessage();
var builder = new BodyBuilder();
myMessage.To.Add(new MailboxAddress(fullName ?? "User", email));
myMessage.From.Add(new MailboxAddress(_dispName, _email));
myMessage.Subject = subject;
builder.HtmlBody = message;
myMessage.Body = builder.ToMessageBody();
using (SmtpClient smtp = new SmtpClient())
{
bool UseSSL = true;
string Host = "just22.justhost.com";
int Port = 465;
await smtp.ConnectAsync(Host, Port, UseSSL).ConfigureAwait(true);
smtp.AuthenticationMechanisms.Remove("XOAUTH2");
smtp.Authenticate(_email, _epass); // Note: only needed if the SMTP server requires authentication
await smtp.SendAsync(myMessage).ConfigureAwait(false);
await smtp.DisconnectAsync(true).ConfigureAwait(false);
}
}
catch (Exception ex)
{
throw ex;
}
}
public Task SendSmsAsync(string number, string message)
{
// Plug in your SMS service here to send a text message.
return Task.FromResult(0);
}
这是我的 Start.cs
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsDevelopment())
{
// For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets();
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddMvc();
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
services.AddDistributedMemoryCache();
services.AddSession();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public async void Configure(IApplicationBuilder app, IHostingEnvironment env,
ILoggerFactory loggerFactory, IServiceProvider serviceProvider, ApplicationDbContext context)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseSession();
app.UseIdentity();
// Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715
app.UseFacebookAuthentication(new FacebookOptions()
{
AppId = Configuration["Authentication:Facebook:AppId"],
AppSecret = Configuration["Authentication:Facebook:AppSecret"]
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
await CreateRoles(context, serviceProvider);
}
private async Task CreateRoles(ApplicationDbContext context, IServiceProvider serviceProvider)
{
var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
// Create a list of roles with both name and normalised name attributes
List<IdentityRole> roles = new List<IdentityRole>();
roles.Add(new IdentityRole { Name = "Admin", NormalizedName = "ADMIN" });
roles.Add(new IdentityRole { Name = "Member", NormalizedName = "MEMBER" });
roles.Add(new IdentityRole { Name = "Moderator", NormalizedName = "MODERATOR" });
// Check if the role already exists
foreach (var role in roles)
{
var roleExist = await RoleManager.RoleExistsAsync(role.Name);
if (!roleExist)
{ // Add it if it doesn't
context.Roles.Add(role);
context.SaveChanges();
}
}
var user = await userManager.FindByEmailAsync("mark****@gmail.com");
if (user != null)
{
var gotRoles = userManager.GetRolesAsync(user);
if (!gotRoles.Equals("Admin"))
{
await userManager.AddToRoleAsync(user, "Admin");
}
}
}
}
我已经检查以确保秘密存在,它确实存在,以及 Facebook 身份验证秘密,这似乎工作得很好。
如果我对密码进行硬编码,则会发送电子邮件。当我设置断点时,我可以看到密码确实为空。我有点难过!
提前致谢。