Search code examples
c#.nethttpmultipartihttphandler

Accessing Multipart HTTP Request Body via C# IHttpHandler


This should be so simple, and I feel like I'm just missing something. I'm new to the HTTP side of this application, so I also feel like I'm shooting in the dark.

We're doing B2B EDI. We'll receive a multi-part POST request. Each part is XML. I need to extract each part and convert each to an XmlDocument.

Here's what I've written.

using System;
using System.Collections.Generic;
using System.Web;
using System.Xml;

namespace Acme.B2B
{
    public class MultipleAttachments : IHttpHandler
    {
        #region IHttpHandler Members

        public bool IsReusable { get { return true; } }

        public void ProcessRequest(HttpContext context)
        {
            var ds = extractDocuments(context.Request);

            return; // Written for debugging only.
        }

        #endregion

        #region Helper Members

        private IEnumerable<XmlDocument> extractDocuments(HttpRequest r)
        {
            // These are here for debugging only.
            var n = r.ContentLength;
            var t = r.ContentType;
            var e = r.ContentEncoding;

            foreach (var f in r.Files)
                yield return (XmlDocument)f;
        }

        #endregion
    }
}

I'm pretty confident that (XmlDocument)f won't work, but I'm still exploring. Oddly enough, setting a break-point on var n = r.ContentLength;, the code never hits that break-point. It just hits the break-point I set on the extraneous return;.

What the heck am I missing?


Solution

  • You need to use HttpPostedFile.InputStream and pass it onto the XDocument constructor:

    foreach (HttpPostedFile postedFile in r.Files)
    {
        yield return XDocument.Load(postedFile.InputStream);
    }
    

    Or if you want XmlDocument:

    foreach (HttpPostedFile postedFile in r.Files)
    {
        yield return new XmlDocument().Load(postedFile.InputStream);
    }