Henrique
Henrique

Reputation: 51

C# Reading multi-part stream

I'm reading a multi-part formdata in an HTTPHandler.

My code:

                var content = new StreamContent(context.Request.InputStream);

            //content.Headers.Add("Content-Type", context.Request.ContentType);
            //content.Headers.TryAddWithoutValidation("Content-Type", context.Request.ContentType);
            //content.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data");
            //content.Headers.Add("Content-Type", "multipart/form-data");
            //content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(context.Request.ContentType);

            // content.Headers.Remove("Content-Type");
            //content.Headers.Add("Content-Type", context.Request.ContentType);~

            content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(context.Request.ContentType);
            if (!content.IsMimeMultipartContent())
            {
                return HttpStatusCode.BadRequest;
            }

            var multipart =await content.ReadAsMultipartAsync();

I always get:

The format of value 'Content-Type: multipart/form-data; boundary=9fc46...................... is invalid

If I don't try to put the content-type I get another error.

Note: The commented lines are other alternatives that I tried without result

Upvotes: 0

Views: 3142

Answers (2)

Henrique
Henrique

Reputation: 51

Working solution:

        var content = (HttpContent)new StreamContent(context.Request.InputStream);
        content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(context.Request.ContentType);
        var multipart = new MultipartMemoryStreamProvider();
        await content.ReadAsMultipartAsync(multipart);

Upvotes: 1

Coesy
Coesy

Reputation: 936

Try setting up a MultPartFormDataContent object with the following boundary and posting this

var content = new MultipartFormDataContent("---------------" + Guid);

I believe the dashes have something to do with the way that boundarys are read in.

Upvotes: 0

Related Questions