如何使用MVC模型绑定从Asp.net MVC中的SendGrid Inbound Parse Webhook获取数据?

时间:2015-02-11 17:13:53

标签: c# asp.net asp.net-mvc sendmail

我正在考虑实施SendMail Inbound Parse Webhook,但发现它们提供的示例似乎远远没有完美的解决方案。

https://sendgrid.com/docs/Code_Examples/Webhook_Examples/csharp.html#-Parse-Webhook

[HttpPost]
public async Task<HttpResponseMessage> Post()
{
  var root = HttpContext.Current.Server.MapPath("~/App_Data");
  var provider = new MultipartFormDataStreamProvider(root);
  await Request.Content.ReadAsMultipartAsync(provider);

  var email = new Email
  {
      Dkim = provider.FormData.GetValues("dkim").FirstOrDefault(),
      To = provider.FormData.GetValues("to").FirstOrDefault(),
      Html = provider.FormData.GetValues("html").FirstOrDefault(),
      From = provider.FormData.GetValues("from").FirstOrDefault(),
      Text = provider.FormData.GetValues("text").FirstOrDefault(),
      SenderIp = provider.FormData.GetValues("sender_ip").FirstOrDefault(),
      Envelope = provider.FormData.GetValues("envelope").FirstOrDefault(),
      Attachments = int.Parse(provider.FormData.GetValues("attachments").FirstOrDefault()),
      Subject = provider.FormData.GetValues("subject").FirstOrDefault(),
      Charsets = provider.FormData.GetValues("charsets").FirstOrDefault(),
      Spf = provider.FormData.GetValues("spf").FirstOrDefault()
  };

  // The email is now stored in the email variable

  return new HttpResponseMessage(HttpStatusCode.OK);
}

这不会以任何对我来说错误的方式使用模型绑定。他们的代码也不会从表单数据中提取附件。

所有的建议,例子和帮助都非常赞赏。

1 个答案:

答案 0 :(得分:7)

这是我目前用于从.net中的SendGrid Inbound Parse Webhook中提取电子邮件数据的最佳解决方案。

请注意,它使用普通的MVC控制器而不是WebApi控制器,因为文件似乎没有附加到WebApi控制器中的请求。

型号:

public class InboundEmailInputModel
{
    public string Headers { get; set; }
    public string Text { get; set; }
    public string Html { get; set; }
    public string From { get; set; }
    public string To { get; set; }
    public List<string> Cc { get; set; }
    public string Subject { get; set; }
    public string Dkim { get; set; }
    public string Spf { get; set; }
    public InboundEmailEnvelopeInputModel Envelope { get; set; }
    public InboundEmailCharsetsInputModel Charsets { get; set; }
    public float SpamScore { get; set; }
    public string SpamReport { get; set; }
    public int Attachments { get; set; }
    public dynamic AttachmentInfo { get; set; }
    public HttpFileCollectionBase AttachmentFiles { get; set; }
    public string SenderIp { get; set; }
}


public class InboundEmailEnvelopeInputModel
{
    public string From { get; set; }
    public List<string> To { get; set; }
}


public class InboundEmailCharsetsInputModel
{
    public string From { get; set; }
    public string To { get; set; }
    public string Cc { get; set; }
    public string Html { get; set; }
    public string Subject { get; set; }
    public string Text { get; set; }
}

控制器

    [System.Web.Mvc.AllowAnonymous]
    [System.Web.Mvc.HttpPost]
    public async Task<HttpResponseMessage> Inbound()
    {
        var inboundEmail = await InboundEmailExtractor.ExtractInboundEmail(Request);

        return new HttpResponseMessage(HttpStatusCode.OK);
    }

静态方法

public static class InboundEmailExtractor
{
    public async static Task<InboundEmailInputModel> ExtractInboundEmail(HttpRequestBase request)
    {
        var serialiser = new JavaScriptSerializer();

        var inboundEmail = new InboundEmailInputModel();

        inboundEmail.Headers = request.Unvalidated.Form["headers"];
        inboundEmail.Text = request.Unvalidated.Form["text"];
        inboundEmail.Html = request.Unvalidated.Form["html"];
        inboundEmail.From = request.Unvalidated.Form["from"];
        inboundEmail.To = request.Unvalidated.Form["to"];
        inboundEmail.Cc = request.Unvalidated.Form["to"].Split(',').ToList();
        inboundEmail.Subject = request.Unvalidated.Form["subject"];
        inboundEmail.Dkim = request.Unvalidated.Form["dkim"];
        inboundEmail.Spf = request.Unvalidated.Form["spf"];

        var envelopeRaw = request.Unvalidated.Form["envelope"];
        if (envelopeRaw != null)
        {
            inboundEmail.Envelope = serialiser.Deserialize<InboundEmailEnvelopeInputModel>(envelopeRaw);
        }

        var charsetsRaw = request.Unvalidated.Form["charsets"];
        if (charsetsRaw != null)
        {
            inboundEmail.Charsets =
                new JavaScriptSerializer().Deserialize<InboundEmailCharsetsInputModel>(charsetsRaw);
        }

        var spamScoreRaw = request.Unvalidated.Form["spam_score"];
        if (spamScoreRaw != null)
        {
            inboundEmail.SpamScore = float.Parse(spamScoreRaw, CultureInfo.InvariantCulture.NumberFormat);
        }

        inboundEmail.SpamReport = request.Unvalidated.Form["spam_report"];

        var attachmentsRaw = request.Unvalidated.Form["attachments"];
        if (attachmentsRaw != null)
        {
            inboundEmail.Attachments = Convert.ToInt32(attachmentsRaw);
        }

        var attachmentInfoRaw = request.Unvalidated.Form["attachment-info"];
        if (attachmentInfoRaw != null)
        {
            inboundEmail.AttachmentInfo = System.Web.Helpers.Json.Decode(attachmentInfoRaw);
        }

        inboundEmail.SenderIp = request.Unvalidated.Form["sender_ip"];

        inboundEmail.AttachmentFiles = request.Files;

        return inboundEmail;
    }
}

评论和改进方法非常受欢迎。