2016-03-08 2 views
0

Я пытаюсь отправить автоматическое сообщение пользователю для завершения регистрации, я тестирую мое приложение на локальном хостежерех чистый sendgrid MVC учетной записи электронной почты проверки

это мой контроллер Регистрация:

// POST: /Account/Register 
[HttpPost] 
[AllowAnonymous] 
[ValidateAntiForgeryToken] 
public async Task<ActionResult> Register(RegisterViewModel model) 
{ 
    if (ModelState.IsValid) 
    { 
     var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; 
     var result = await UserManager.CreateAsync(user, model.Password); 
     if (result.Succeeded) 
     { 
      // Comment the following line to prevent log in until the user is confirmed. 
      // await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false); 

      // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 
      // Send an email with this link 
      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>"); 

      // Uncomment to debug locally 
      // TempData["ViewBagLink"] = callbackUrl; 

      ViewBag.Message = "Check your email and confirm your account, you must be confirmed " 
          + "before you can log in."; 

      return View("Info"); 
      //return RedirectToAction("Index", "Home"); 


     } 
     AddErrors(result); 
    } 

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

это мой Email класс обслуживания

public class EmailService : IIdentityMessageService 
{ 
    public async Task SendAsync(IdentityMessage message) 
    { 
     // Create the email object first, then add the properties. 
     var myMessage = new SendGridMessage(); 

     // this defines email and name of the sender 
     myMessage.From = new MailAddress("[email protected]", "My Example Admin"); 

     // set where we are sending the email 
     myMessage.AddTo(message.Destination); 

     myMessage.Subject = message.Subject; 

     // make sure all your messages are formatted as HTML 
     myMessage.Html = message.Body; 

     // Create credentials, specifying your SendGrid username and password. 
     var credentials = new NetworkCredential(
      ConfigurationManager.AppSettings["SendGridLogin"], 
      ConfigurationManager.AppSettings["SendGridPassword"] 
               ); 

     // Create an Web transport for sending email. 
     var transportWeb = new Web(credentials); 

     // Send the email. 
     await transportWeb.DeliverAsync(myMessage); 
    } 
} 

Я использую SendGridSmtpApi 1.3.1 & SendGrid C# библиотека Чиленто 6.3.4. Где проблема, почему это не работает?

+0

прописали вам счет с SendGrid? – severin

+0

есть. У меня активная учетная запись sendgrid. –

+0

Хорошо. Я не уверен, что вы можете отправлять электронную почту, используя только учетные данные, возможно, вам придется создать ApiKey в своей учетной записи SendGrid. Лично я отправляю использование только ApiKey, например: var transportWeb = new SendGrid.Web (); – severin

ответ

1

Поскольку вы выполняете асинхронный вызов, возможно, ваша программа выйдет до того, как вызов будет завершен. Таким образом, необходимо следующее, если вы хотите, чтобы заблокировать, пока вызов не будет завершен до вашей программы продолжается:

transportWeb.DeliverAsync(message).Wait(); 

В качестве альтернативы, вы можете «Подождите() или результат» от вызывающей функции в зависимости от желаемого результата ,

Для получения дополнительной информации, проверьте следующее:

What happens while waiting on a Task's Result?

Await on a completed task same as task.Result?

+1

Хотя этот код может ответить на вопрос, предоставляя дополнительный контекст относительно * why * и/или * как * этот код отвечает на вопрос, улучшает его долгосрочную ценность. –

+1

Спасибо за продолжение Benjamin! Я отредактировал свой ответ, надеюсь, будет более полезным. –

Смежные вопросы