控制未点击Custom EmailService的SendAsync功能:MVC电子邮件确认

时间:2016-01-12 09:56:12

标签: asp.net-mvc authentication identity

我在Visual Studio 2013中创建了一个新的MVC项目。我注意到IdentityConfig.cs文件丢失了。我听说微软从较新版本的ASP.NET身份中删除了它。此文件(如果存在)用于定义EmailService类。

所以我实现了自己的EmailService课程。代码看起来像这样

//EmailService.cs
public class EmailService : IIdentityMessageService
{
    public async Task SendAsync(IdentityMessage message)
    {
        await configGMailAsync(message);
    }
    private static async Task configGMailAsync(IdentityMessage message)
    {
       //mailing code
    }
} 

在我的AccountController中,我有以下Register方法,该方法调用UserManager.SendEmailAsync()方法。

    // POST: /Account/Register
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser() { UserName = model.UserName };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                await SignInAsync(user, isPersistent: false);

                var provider = new DpapiDataProtectionProvider("myAppName");
                UserManager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(provider.Create("EmailConfirmation"));
                string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                var callbackUrl = Url.Action("ConfirmEmail", "Account",
                    new { userId = user.Id, code = code },
                    protocol: Request.Url.Scheme);


                await UserManager.SendEmailAsync(user.Id,
                    "Confirm your account", "Please confirm your account by clicking <a href=\""
                    + callbackUrl + "\">here</a>");

                return RedirectToAction("Index", "Home");
            }
            else
            {
                AddErrors(result);
            }
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

但是,在调用UserManager.SendEmailAsync()之后,控件(调试器)永远不会访问SendAsync()类的EmailService函数。

我有另一个项目,其中IdentityConfig.cs在项目创建时自动添加。在调用UserManager.SendEmailAsync()之后,控件会点击SendAsync()功能。

我在这里缺少什么?

2 个答案:

答案 0 :(得分:2)

事实证明,在发送邮件之前,您必须使用UserManager课程注册您的服务。在UserManager.SendEmailAsync()上方添加以下行后,SendAsync()功能成功获取:

UserManager.EmailService = new EmailService();

这是完整的功能,包括新添加的行

// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser() { UserName = model.UserName };
        var result = await UserManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {
            await SignInAsync(user, isPersistent: false);

            var provider = new DpapiDataProtectionProvider("myAppName");
            UserManager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(provider.Create("EmailConfirmation"));
            string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

            var callbackUrl = Url.Action("ConfirmEmail", "Account",
                new { userId = user.Id, code = code },
                protocol: Request.Url.Scheme);

            UserManager.EmailService = new EmailService();

            await UserManager.SendEmailAsync(user.Id,
                "Confirm your account", "Please confirm your account by clicking <a href=\""
                + callbackUrl + "\">here</a>");

            return RedirectToAction("Index", "Home");
        }
        else
        {
            AddErrors(result);
        }
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}

答案 1 :(得分:0)

我在VS 2017中创建了一个包含单个用户帐户的新Web API 2项目。IdentityConfig.cs存在,但它没有EmailService类。如果是这种情况,并且每次您不想使用此功能时都不想写UserManager.EmailService = new EmailService();,则可以在此处添加。

public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
    var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
    manager.EmailService = new EmailService();