Я нуб .NET и использую .NET Core 2.2
и sendgrid-csharp
пакет NuGet с Visual Studio 2019 Community Edition
У меня есть форма, которая отправляется с помощью ajax
вызова метода контроллера, который отправляет электронное письмо через SendGrid
. Письмо успешно отправлено, и я могу записать ответ. Однако ответ никогда не возвращается на вызов ajax
и просто зависает в браузере до истечения времени ожидания.
Я хотел бы вернуть response.StatusCode
ответа SendGrid
на вызов ajax
.
HomeController.cs
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Collections.Generic;
using Microsoft.AspNetCore.Hosting;
using System.IO;
using SendGrid;
using SendGrid.Helpers.Mail;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Identity.UI.Services;
namespace MyProject.Controllers {
public class HomeController:Controller {
private readonly IHostingEnvironment _hostingEnvironment;
public HomeController(IHostingEnvironment hostingEnvironment) {
_hostingEnvironment = hostingEnvironment;
}
[HttpPost]
public async Task<JsonResult> SendMessageEmail() {
using (var reader = new System.IO.StreamReader(Request.Body)) {
var formData = JsonConvert.DeserializeObject<Dictionary<string, string>>(reader.ReadToEnd());
formData["subject"] = "Email Subject";
formData["body"] = "Email Body";
EmailSender emailSenderService = new EmailSender();
var response = await emailSenderService.Execute(formData["fromemail"], formData["toemail"], formData["subject"], formData["body"], formData["body"]);
Console.WriteLine("-----------------");
Console.WriteLine("response: ", response);
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.Headers);
Console.ReadLine();
Console.WriteLine("-----------------");
return new JsonResult(response.StatusCode);
}
}
}
internal class EmailSender {
public async Task<Response> Execute(string From, string To, string subject, string plainTextContent, string htmlContent) {
var apiKey = "MY_SEND_GRID_KEY";
var client = new SendGridClient(apiKey);
var from = new EmailAddress(From);
var to = new EmailAddress(To);
var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
var response = await client.SendEmailAsync(msg);
return response;
}
}
}
form.js
$(document).on('submit', 'form#email-message-form', function(event) {
event.stopImmediatePropagation();
event.stopPropagation();
event.preventDefault();
var emailMessageForm = $('form#email-message-form');
var messageTo = $('form#email-message-form #message-to');
var messageFrom = $('form#email-message-form #message-from');
var data = {};
data.toemail = messageTo.val()
data.fromemail = messageFrom.val()
var request = $.ajax({
url: "/Home/SendMessageEmail",
method: "POST",
data: JSON.stringify(data),
contentType: 'application/json',
dataType: "json",
cache: false,
async: false
}).done(function (msg) {
console.log('Success: ', msg);
}).fail(function (jqXHR, textStatus) {
console.log("Send email method failed: " + textStatus);
});
});