【问题标题】:Call WebAPI method from MVC method passing Mail Message从传递邮件消息的 MVC 方法调用 WebAPI 方法
【发布时间】:2017-06-09 14:35:43
【问题描述】:

我的 MVC 控制器中有一个方法,我试图从中调用 API 以发送电子邮件(邮件消息在 MVC 方法中生成)

创建邮件消息如下,效果很好。

    public static MailMessage CreateMailMessage(string from,
        string to,
        string cc,
        string bcc,
        string subject,
        string body,
        List<Attachment> attachments,
        string differentServer,
        bool eatError)
    {
        MailMessage mm = new MailMessage();
        mm.From = new MailAddress(from);
        mm.Subject = subject;
        mm.Body = body;
        mm.IsBodyHtml = true;

        //send to multiple addresses separated by semi-colon or comma      
        if (!string.IsNullOrEmpty(to))
        {
            var toAddresses = to.Split(new char[] { ';', ',' });
            foreach (string toAddress in toAddresses)
            {
                if (!string.IsNullOrWhiteSpace(toAddress))
                    mm.To.Add(toAddress);
            }
        }

        if (!string.IsNullOrEmpty(cc))
        {
            mm.CC.Add(cc);
        }

        if (!string.IsNullOrEmpty(bcc))
        {
            mm.Bcc.Add(bcc);
        }

        if (attachments != null)
        {
            foreach (Attachment attachment in attachments)
            {
                mm.Attachments.Add(attachment);
            }
        }
        return mm;
    }

但是,为了发送电子邮件,我需要编写并调用 WebAPI 方法 - 发送电子邮件很好 - 只是不确定如何将邮件消息和其他一些属性发布到 WebAPI 方法?

所以我现在的 WebAPI 方法是这样的:

    /// <summary>
    /// Method to email the Report
    /// </summary>
    /// <returns></returns>
    [HttpPost]
    [Route("api/Document/EmailReport/")]
    public HttpResponseMessage EmailFarmFeatures([FromBody]MailMessage email)
    {
        return Request.CreateResponse(HttpStatusCode.OK);
    }

我正在尝试从 MVC 方法调用此 WebAPI,如下所示:

private void EmailReport(string reportName, byte[] bytes)
{
  ContentType ct = new ContentType(MediaTypeNames.Application.Octet);
  var attachments = new List<Attachment>();
  var attach = new Attachment(new MemoryStream(bytes), ct);
  attach.ContentDisposition.FileName = reportName;
  attachments.Add(attach);

  string strFrom = ConfigurationManager.AppSettings["FromEmail"];
  string strTo = ConfigurationManager.AppSettings["ToEmail"];

  string subject = string.Format("Customer Report - {0}", customerId);
  string body = string.Format("Report for Customer {0} attached.", customerId);
  string mailServer = ConfigurationManager.AppSettings["SmtpServer"];

  MailMessage message = EmailHelper.CreateMailMessage(strFrom, strTo, "", "", subject, body, attachments, mailServer, false);

  using (var client = new HttpClient())
  {
    var requestBody = JsonConvert.SerializeObject(message);
    var postRequest = new StringContent(requestBody, Encoding.UTF8, "application/json");

    var response = client.PostAsync("http://localhost/myWS/api/Document/EmailReport/", postRequest).GetAwaiter().GetResult();

    if (response.StatusCode != HttpStatusCode.OK)
    {
      throw new Exception("Error occured emailing report");
    }
  }
}

我目前在这一行遇到错误:

var requestBody = JsonConvert.SerializeObject(message);

[InvalidOperationException: Timeouts are not supported on this stream.]
   System.IO.Stream.get_ReadTimeout() +57
   GetReadTimeout(Object ) +81
   Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target) +114

[JsonSerializationException: Error getting value from 'ReadTimeout' on 'System.IO.MemoryStream'.]
   Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target) +274

我认为这与尝试对内存流附件进行序列化有关,但我不确定要确保此附件包含在对 API 方法的 POST 请求中的修复方法

【问题讨论】:

  • 按照您自己的建议,创建一个表示 MailMessage 的可序列化自定义对象(包括邮件消息字段)并通过 post 请求发送
  • @esiprogrammer - 嗨,我对问题进行了一些更新 - 我在尝试序列化时遇到问题
  • Web API 方法是否与 MVC 在同一站点中?还是它们托管在不同的网站上?
  • @mason - 托管在 IIS 中的单独网站中(无法更改该架构)但是我正在为两者编写代码

标签: c# .net asp.net-mvc asp.net-mvc-4 asp.net-web-api


【解决方案1】:

MailMessage 不可序列化只需创建一个表示邮件消息的单独常规对象。

看看这个帖子,我想这正是你需要的:

(https://discuss.hangfire.io/t/help-sending-email-mailmessage-deserialize-problem/354/5)[https://discuss.hangfire.io/t/help-sending-email-mailmessage-deserialize-problem/354/5]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-15
    • 1970-01-01
    • 2011-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多