I confirm the Token via email and when I confirm the link in my inbox, I go to a new tab, I wanted to make the switch in the same window as the mail!
The usual implementation of OWIN / KAtana works, the original sending letter is taken: https: // blogs. msdn.microsoft. com / webdev / 2014/02/18 / adding-two-factor-authentication-to-an-application-using-asp-net-identity / # (spaces must be removed)
(The first 9 points are made, the usual confirmation, without a pin code)
Those. the method generates a token and sends a link to the mail. While the link on the server is ok, but when it comes to the mail, target = "_blank" , although I explicitly send target = "_self" from the server
Some code does not mix:
[HttpPost] [ValidateAntiForgeryToken] public ActionResult Register(RegisterModel model) { if (ModelState.IsValid) { ApplicationUser user = new ApplicationUser { UserName = model.Email, Email = model.Email, Year = model.Year }; //Если пытаемся ввести уже существующий E-mail!!! ApplicationUser user2 = UserManager.Find(model.Email, model.Password); if (user2 != null) // если есть! { ModelState.AddModelError("HasUserToDb", "Такой пользователь уже есть базе!"); return PartialView("Register"); } IdentityResult result = UserManager.Create(user, model.Password); if (result.Succeeded) { //генерим токен для подтверждения регистрации var code = UserManager.GenerateEmailConfirmationToken(user.Id); //создаем ссылку для подтверждения var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); //шлем письмо +++ТУТ ПРОБЛЕМА с "_self"+++ string textEmail = "При регистрации учетной записи " + user.Email + " был указан Ваш email.<hr />Для завершения регистрации перейдите по ссылке: <a href=\"" + callbackUrl + "\" target=\"_self\">Завершить регистрацию</a>"; UserManager.SendEmail(user.Id, "Подтверждение электронной почты", textEmail); return PartialView("ShowEmail"); //return JavaScript("OnSuccess();"); } else //не создаст Юзера { . . . Update
@ Erkin So, this is all there is:
[HttpPost] [ValidateAntiForgeryToken] public ActionResult Register(RegisterModel model) { if (ModelState.IsValid) { ApplicationUser user = new ApplicationUser { UserName = model.Email, Email = model.Email, Year = model.Year }; //Если пытаемся ввести уже существующий E-mail!!! ApplicationUser user2 = UserManager.Find(model.Email, model.Password); if (user2 != null) // если есть! { ModelState.AddModelError("HasUserToDb", "Такой пользователь уже есть базе!"); return PartialView("Register"); } IdentityResult result = UserManager.Create(user, model.Password); if (result.Succeeded) { //генерим токен для подтверждения регистрации var code = UserManager.GenerateEmailConfirmationToken(user.Id); //создаем ссылку для подтверждения var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); //шлем письмо string textEmail = "При регистрации учетной записи " + user.Email + " был указан Ваш email.<hr />Для завершения регистрации перейдите по ссылке: <a href=\"" + callbackUrl + "\">Завершить регистрацию</a>"; UserManager.SendEmail(user.Id, "Подтверждение электронной почты ", textEmail); return PartialView("ShowEmail"); //return JavaScript("OnSuccess();"); } else //не создаст Юзера { . . . } . . .
And Actually the UserManager.SendMail method itself, which is overridden in EmailService : IIdentityMessageService
Here he is:
public class EmailService : IIdentityMessageService { public Task SendAsync(IdentityMessage message) { //настройка логина, пароля отправителяz var from = "ZZZZZ@yandex.by"; var pass = "ZZZZZ33241"; //адрес и порт smtp - сервера, с которого мы и будем отправлять письмо SmtpClient client = new SmtpClient("smtp.yandex.ru", 25); client.DeliveryMethod = SmtpDeliveryMethod.Network; client.UseDefaultCredentials = false; //управляет отправкой учетных данных DefaultCredentials вместе с запросами. client.Credentials = new NetworkCredential(from, pass); //Возвращает или задает учетные данные, используемые для проверки подлинности отправителя. client.EnableSsl = true; //Указывает, использует ли SmtpClient протокол SSL для шифрования подключения. // создаем письмо: message.Destination - адрес получателя var mail = new MailMessage(from, message.Destination); //Представляет сообщение электронной почты, которое может быть отправлено с помощью класса SmtpClient. mail.Subject = message.Subject; //Получает или задает строку темы для данного сообщения электронной почты. mail.Body = "<head><base target =\"_self\"></head>" + message.Body; //Получает или задает основную часть сообщения. mail.IsBodyHtml = true; //Получает или задает значение, показывающее, имеет ли основная часть почтового сообщения формат HTML. return client.SendMailAsync(mail); //Отправляет указанное сообщение SMTP-серверу для доставки в качестве асинхронной операции.9+ } } 
