如何修复电子邮件确认 - 在 .NET Core 中,它不起作用

Oma*_*led 4 c# asp.net-identity asp.net-core-3.0

我已经有一个注册操作

public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
            var useremail = _userManager.Users.FirstOrDefault(u => u.Email.ToLower() == Input.Email.ToLower());

            if (useremail == null)
            {
                returnUrl = returnUrl ?? Url.Content("~/");
                ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();

                if (ModelState.IsValid)
                {
                    var user = new IdentityUser { UserName = Input.UserName, Email = Input.Email };
                    var result = await _userManager.CreateAsync(user, Input.Password);
                    if (result.Succeeded)
                    {
                        _logger.LogInformation("User created a new account with password.");

                        var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                        code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                        var callbackUrl = Url.Page(
                            "/Account/ConfirmEmail",
                            pageHandler: null,
                            values: new { area = "Identity", userId = user.Id, code = code },
                            protocol: Request.Scheme);

                        await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                            $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                        if (_userManager.Options.SignIn.RequireConfirmedAccount)
                        {
                            return RedirectToPage("RegisterConfirmation", new { email = Input.Email });
                        }
                        else
                        {
                            await _signInManager.SignInAsync(user, isPersistent: false);
                            return LocalRedirect(returnUrl);
                        }
                    }

                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError(string.Empty, error.Description);
                    }
                }
            }
            // If we got this far, something failed, redisplay form
            ViewData["EmailExists"] = "Try another email that one is used";

            return Page();
}
Run Code Online (Sandbox Code Playgroud)

然后我创建了sendgrid用户和密钥并通过CMD注册它们,然后我创建了发送电子邮件的动作

public class EmailSender : IEmailSender
{
        public EmailSender(IOptions<AuthMessageSenderOptions>optionsAccessor)
        {
            Options = optionsAccessor.Value;
        }

        public AuthMessageSenderOptions Options { get; }

        public Task SendEmailAsync (string email , string subject , string message)
        {
            return Excute(Options.SendGridKey,subject,message,email);
        }

        private Task Excute(string apiKey, string subject, string message, string email)
        {
            var client = new SendGridClient(apiKey);
            var msg = new SendGridMessage()
            {
                From = new EmailAddress("darydress@yahoo.com", "dary dress"),
                Subject = subject,
                PlainTextContent = message,
                HtmlContent = message
            };

            msg.AddTo(new EmailAddress(email));
            msg.SetClickTracking(false, false);

            return client.SendEmailAsync(msg);
        }
}
Run Code Online (Sandbox Code Playgroud)

然后在startup.cs

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
          options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));
    services.AddIdentity<IdentityUser, IdentityRole>( options => options.SignIn.RequireConfirmedAccount = true)
                .AddDefaultUI()
                .AddDefaultTokenProviders()
                .AddEntityFrameworkStores<ApplicationDbContext>();
    services.AddControllersWithViews();
    services.AddRazorPages();
    services.AddMvc();
    services.AddTransient<IEmailSender, EmailSender>();
    services.Configure<AuthMessageSenderOptions>(Configuration);
    services.AddPaging();
    services.ConfigureApplicationCookie(o => {
                o.ExpireTimeSpan = TimeSpan.FromDays(5);
                o.SlidingExpiration = true;
            });
    services.AddMvc(options =>
            {
                options.Filters.Add(new RequireHttpsAttribute());
            });
    services.ConfigureApplicationCookie(options =>
            {
                options.AccessDeniedPath = new Microsoft.AspNetCore.Http.PathString("/Main/AccessDenied");
            });
}
Run Code Online (Sandbox Code Playgroud)

但是注册后发送电子邮件不起作用给了我一些我需要确认我的电子邮件并给我链接以确认我的电子邮件但没有将其发送到gmail的词

有没有人有想法?

我从微软 https://docs.microsoft.com/en-us/aspnet/core/security/authentication/accconfirm?view=aspnetcore-3.1&tabs=visual-studio

小智 7

当我使用个人用户帐户创建新的 Web 应用程序时,这非常有效,但我注意到当您构建身份并覆盖所有页面以控制现有应用程序时,您遇到的行为是常见的。

这是我修复它的方法:

如果您打开文件Areas/Identity/Pages/Account/RegisterConfirmation.cshtml.cs查找 comment Once you add a real email sender, you should remove this code that lets you confirm the account,请在 return Page() 语句之前注释该行下方的所有内容,这应该可以完成工作。


Oma*_*led 1

“已解决”我询问了 Sendgrid,并被告知我不能使用我的 yahoo 电子邮件(或 gmail,...)作为发件人电子邮件;这是答案的一部分:“雅虎遵守名为 DMARC 的电子邮件安全标准。DMARC 指示电子邮件提供商拒绝发件人域是雅虎域的邮件,但该邮件源自未经批准的域服务器/服务。” 所以我需要使用我自己的邮件域;