2017-11-24 21 views
0

デフォルトのASP.NET MVC、IDテンプレートを使用しています...クライアントに確認メールを送信します。SendEmailAsyncのバージョンが異なる

新しいプロジェクトテンプレートが付属してデフォルトの実装では、AccountController.csに登録する方法があります

public async Task<ActionResult> Register(RegisterViewModel model) 
    { 
     if (ModelState.IsValid) 
     { 
      var user = new ApplicationUser { UserName = model.Email.Trim(), Email = model.Email.Trim(), FirstName = model.FirstName.Trim(), LastName = model.LastName.Trim() }; 
      var result = await UserManager.CreateAsync(user, model.Password); 
      if (result.Succeeded) 
      { 
       await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false); 

       // 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); 
       string message = "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"; 
       await UserManager.SendEmailAsync(user.Id, "Confirm your account", HttpUtility.UrlEncode(message)); 

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

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

UserManager.SendEmailAsyncへの呼び出しがあり、今、この方法はMicrosoft.AspNet.Identityに定義されています私はそれを変更したくないです。

実際のセンド・メール機能はので、私はmessage.bodyを電子メールで送信したくない...今、あなたが見るように、私は電子メールを送信するSendgridを使用していますIdentityConfig.cs

public class SendGridEmailService : IIdentityMessageService 
{ 
    public async Task SendAsync(IdentityMessage message) 
    { 
     var apiKey = ConfigurationManager.AppSettings["SendGridApiKey"]; 
     var client = new SendGridClient(apiKey); 
     var msg = new SendGridMessage() 
     { 
      From = new EmailAddress("[email protected]", "DX Team"), 
      Subject = message.Subject, 
      PlainTextContent = message.Body, 
      HtmlContent = message.Body 
     }; 

     msg.TemplateId = /* I want to pass templateId here */ 
     msg.Personalizations[0].Substitutions.Add("confirmurl", /* I want to pass Username here */); 
     msg.Personalizations[0].Substitutions.Add("confirmurl", /* I want to pass confirm url here */); 

     msg.AddTo(new EmailAddress("[email protected]", "Test User")); 
     var response = await client.SendEmailAsync(msg); 

    } 
} 

に..です私はいくつかのテンプレートを作っており、私はテンプレートで置き換えられるusernameのようないくつかの置換タグを使ってteplate Idを渡したいと思っています。

だから、私は

SendGridAsync(SendGridMessage message) 

のようなものは、このメソッドを追加することが可能ですので、私はSendAsyncを呼び出すようにしてSendGridAsyncを呼び出すようにするときとき選択することができますしたい...このジェネリックSendAsyncメソッドをしたくないですか?

+0

私は電子メール*内容の建物をリファクタリングになります*別々にサービス。それを呼び出すと、結果を 'UserManager.SendEmailAsync(...)'に渡します。サービスには、送信する電子メールの種類ごとの実装の詳細が含まれています。 –

+0

Brendanありがとうございます、どうすればいいですか? SendAsyncは、宛先、件名、本文を持つIdentityMessageのみを受け取ります...私が行っているのはSendGridMessageを構築していて、SendGridAsync(SendGridMessageメッセージ)のようなものが必要ですが、これを追加する方法はわかりません... – Sarhang

+1

Sengridテンプレートに問題があります。あなたは電子メールを送るために 'UserManager.SendEmailAsync(...)'を使う必要はありません**。あなた自身のサービスから電子メールを送ることができます - あなたの実装は 'IIdentityMessageService'を実装する必要はありません。また、あなたは 'UserManager.SendEmailAsync()'への呼び出しを変更したくないと述べています。なぜそうではありませんか? –

答えて

1

組み込みのメールサービスを使用する必要はありません。特に、もう少し複雑なことをしたい場合は特にそうです。あなたのDIフレームワークで

public interface IMyMessageService 
{ 
    Task SendConfirmationMessage(string confirmUrl, string to) 
    // define methods for other message types that you want to send 
} 

public class MyMessageServie : IMyMessageService 
{ 
    public async Task SendConfirmationMessage(string confirmUrl, string to) 
    { 
     var apiKey = ConfigurationManager.AppSettings["SendGridApiKey"]; 
     var client = new SendGridClient(apiKey); 
     var msg = new SendGridMessage() 
     { 
      From = new EmailAddress("[email protected]", "DX Team"), 
      Subject = message.Subject, 
      PlainTextContent = message.Body, 
      HtmlContent = message.Body 
     }; 

     msg.TemplateId = /* I want to pass templateId here */ 
     msg.Personalizations[0].Substitutions.Add("confirmurl", confirmUrl); 

     msg.AddTo(new EmailAddress(to, "Test User")); 
     var response = await client.SendEmailAsync(msg); 

    } 
} 

登録IMyMessageService、および電子メールは(例えば、AccountController)から送信されているコントローラに注入:

は、独自のメッセージングサービスを定義します。

今、あなたのレジスタアクションは(私はIMyMessageServiceを注入し、_myMessageServiceでインスタンスを持ってきたと仮定し)、次のようになります。

public async Task<ActionResult> Register(RegisterViewModel model) 
{ 
    if (ModelState.IsValid) 
    { 
     var user = new ApplicationUser { UserName = model.Email.Trim(), Email = model.Email.Trim(), FirstName = model.FirstName.Trim(), LastName = model.LastName.Trim() }; 
     var result = await UserManager.CreateAsync(user, model.Password); 
     if (result.Succeeded) 
     { 
      await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false); 

      // 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); 

      // USE YOUR MESSAGE SERVICE 
      await _myMessageService.SendConfirmationMessage(callbackUrl, user.Email); 

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

    // If we got this far, something failed, redisplay form 
    return View(model); 
} 
関連する問題