MVC 5 WebApi FormDataCollection duplicates data as NameValueCollection

530 Views Asked by At

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 = [email protected]
sender = [email protected]
subject = subject
from = UserName <[email protected]>

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 <[email protected]>,UserName <[email protected]>

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.

0

There are 0 best solutions below