0

I have an external service that POSTs emails to an MVC 5 WebApi endpoint as form data. Since the fields can change, I am trying to receive the POST body as a FormDataCollection. When I call the ReadAsNameValueCollection method, the results are inconsistent with the POSTed data.

For example, the beginning of the raw form data looks like this:

recipient=test%40example.com&sender=user%40gmail.com&subject=subject&from=UserName+%3Cuser%40gmail.com%3E

After some URL decoding the values should be:

recipient = test@example.com
sender = user@gmail.com
subject = subject
from = UserName <user@gmail.com>

But when I convert to a NameValueCollection and iterate over the keys and values, a couple of the values are returned as two copies of the data separated by a comma:

subject = subject,subject
from = UserName <user@gmail.com>,UserName <user@gmail.com>

There are 26 fields in my test emails (it would vary if there were attachments, for example), and this problem only affects the subject and from fields, as shown above -- both of which are just plain text, nothing special about them.

Anybody know what causes this or how to avoid it?

Edit: Posting code, but I didn't bother earlier because it's literally as simple as taking the input parameter and converting. (BlobWriter is just a helper class to write a string to Azure blob storage.)

public async Task<IHttpActionResult> ReceiveEmail(FormDataCollection postBody)
{
    NameValueCollection email = postBody.ReadAsNameValueCollection();

    // Debug: dump key/vals
    StringBuilder sb = new StringBuilder();
    foreach(string key in email.AllKeys) sb.AppendLine($"{key} == {email[key]}");
    await BlobWriter.Write("debug-container", "email.txt", sb.ToString());

    return Ok();
}

Edit 2: I should also note, requesting a specific key/value from the FormDataCollection (rather than dumping them iteratively) confirms the incorrect content. For example, postBody.Get("subject") yields subject,subject as the stored value.

McGuireV10
  • 9,572
  • 5
  • 48
  • 64
  • Maybe the issue is in your code but you have not posted your code so hard to say. – CodingYoshi Dec 16 '17 at 22:36
  • I can't see that it helps, but it's up there. The source for [FormDataCollection](https://github.com/ASP-NET-MVC/aspnetwebstack/blob/master/src/System.Net.Http.Formatting/Formatting/FormDataCollection.cs) is simple enough, I suppose the real culprit is probably in [FormUrlEncodedParser](https://github.com/ASP-NET-MVC/aspnetwebstack/blob/master/src/System.Net.Http.Formatting/Formatting/Parsers/FormUrlEncodedParser.cs). Maybe I'll pick through it after I've had my coffee. – McGuireV10 Dec 17 '17 at 12:37

0 Answers0