尝试发送确认电子邮件时,身份电子邮件服务未触发

时间:2018-09-20 16:38:52

标签: c# webforms asp.net-identity

我一直在修改WebForms应用程序中ASP.Net Identity的实现。我的修改导致我的EmailService的SendAsync函数无法启动,我不确定为什么。我唯一能想到的是如何在注册页面上实例化UserManager。在我执行 var manager = Context.GetOwinContext()。GetUserManager(); 之前,现在我正在执行 var manager = new DecisionLogicIdentity.ApplicationUserManager(userStore); 。我在UserManager的Create函数中设置了EmailService(manager.EmailService = new EmailService();)。在我更改UserManager的方式之前,SendGrid的实现一直在工作。有人知道我在这里缺少什么吗?

Register.aspx.cs:

protected void CreateUser_Click(object sender, EventArgs e)
{
    var context = HttpContext.Current.GetOwinContext().Get<DecisionLogicIdentity.ApplicationDbContext>();
    var userStore = new DecisionLogicIdentity.UserStore<DecisionLogicIdentity.ApplicationUser>(context)
    {
        CompanyId = Int32.Parse(CompanyId.Text)
    };
    var manager = new DecisionLogicIdentity.ApplicationUserManager(userStore);
    var signinManager = new DecisionLogicIdentity.ApplicationSignInManager(manager, HttpContext.Current.GetOwinContext().Authentication);

    var provider = new DpapiDataProtectionProvider("SampleAppName");
    manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser, int>(provider.Create("SampleTokenName"));

    var user = new DecisionLogicIdentity.ApplicationUser()
    {
        CompanyId = Int32.Parse(CompanyId.Text),
        UserName = Email.Text,
        Email = Email.Text,
        IsExpired = false,
        IsDeleted = false
    };

    IdentityResult result = manager.Create(user, Password.Text);

    if (result.Succeeded)
    {
        user = userStore.FindByEmailAsync(user.Email).GetAwaiter().GetResult();

        string code = manager.GenerateEmailConfirmationToken(user.Id);
        string callbackUrl = IdentityHelper.GetUserConfirmationRedirectUrl(code, user.Id, Request);

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

        //signinManager.SignIn(user, isPersistent: false, rememberBrowser: false);
        //signinManager.PasswordSignIn(Email.Text, Password.Text, true, shouldLockout: true);

        IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
    }
    else
    {
        ErrorMessage.Text = result.Errors.FirstOrDefault();
    }
}

EmailService:

public class EmailService : IIdentityMessageService
{
    public async Task SendAsync(IdentityMessage message)
    {
        await configSendGridasync(message);
    }

    // Use NuGet to install SendGrid (Basic C# client lib) 
    private async Task configSendGridasync(IdentityMessage message)
    {
        SendGridClient client = new SendGridClient(ConfigurationManager.AppSettings["SendGrid--APIKey"].ToString());
        var msg = MailHelper.CreateSingleEmail(new SendGrid.Helpers.Mail.EmailAddress("someemail@somedomain.com"),
            new SendGrid.Helpers.Mail.EmailAddress(message.Destination),
            message.Subject,
            message.Body,
            message.Body);

        msg.Attachments = null;

        await client.SendEmailAsync(msg);
    }
}

ApplicationUserManager:

public class ApplicationUserManager : UserManager<ApplicationUser, int>
{
    public ApplicationUserManager(IUserStore<ApplicationUser, int> store)//, IIdentityMessageService emailService)
        : base(store)
    {
    }

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

        // Configure validation logic for usernames
        manager.UserValidator = new UserValidator<ApplicationUser, int>(manager)
        {
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = true
        };

        // Configure validation logic for passwords
        manager.PasswordValidator = new PasswordValidator
        {
            RequiredLength = 6,
            RequireNonLetterOrDigit = true,
            RequireDigit = true,
            RequireLowercase = true,
            RequireUppercase = true,
        };

        // Configure user lockout defaults
        manager.UserLockoutEnabledByDefault = true;
        manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromSeconds(Int32.Parse(ConfigurationManager.AppSettings["UserLockoutMinutes"].ToString()));
        manager.MaxFailedAccessAttemptsBeforeLockout = Int32.Parse(ConfigurationManager.AppSettings["UserMaxLoginAttempts"].ToString());

        // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
        // You can write your own provider and plug it in here.
        manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser, int>
        {
            MessageFormat = "Your security code is {0}"
        });
        manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser, int>
        {
            Subject = "Security Code",
            BodyFormat = "Your security code is {0}"
        });
        manager.EmailService = new EmailService();
        manager.SmsService = new SmsService();

        var dataProtectionProvider = options.DataProtectionProvider;
        if (dataProtectionProvider != null)
        {
            var provider = new DpapiDataProtectionProvider("SampleAppName");
            manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser, int>(provider.Create("SampleTokenName"));
        }
        return manager;
    }
}

1 个答案:

答案 0 :(得分:0)

万一有人需要答案,我可以通过修改UserManager来获得此功能:

return $this->belongsTo('App\Models\ContractStatuses', 'status');

以及在实例化UserManager时:

public class ApplicationUserManager : UserManager<ApplicationUser, int>
{
    public ApplicationUserManager(IUserStore<ApplicationUser, int> store, IIdentityMessageService emailService)
        : base(store)
    {
        this.EmailService = emailService;
    }
...