Я модифицировал свою реализацию ASP.Net Identity в своем приложении WebForms.Мои изменения привели к тому, что функция SendAsync моего EmailService не сработала, и я не уверен почему.Единственное, о чем я могу думать, это как я создаю экземпляр UserManager на странице регистрации.Раньше я делал var manager = Context.GetOwinContext (). GetUserManager (); , а теперь я делаю var manager = new DecisionLogicIdentity.ApplicationUserManager (userStore); .Я устанавливаю EmailService в функции «Создать» UserManager (manager.EmailService = new EmailService ();).Реализация SendGrid работала до того, как я изменил способ вызова UserManager.Кто-нибудь знает, что мне здесь не хватает?
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;
}
}