2

I'm using this code to process a file upload to a web api:

[HttpPost]
public async Task<IHttpActionResult> Post(string provider)
{  
    if (!Request.Content.IsMimeMultipartContent())
        throw new Exception();

    var streamProvider = new MultipartMemoryStreamProvider();
    await Request.Content.ReadAsMultipartAsync(streamProvider); // FAILS HERE
    foreach (var file in streamProvider.Contents)
    {
        var imageFilename = file.Headers.ContentDisposition.FileName.Trim('\"');
        var imageStream = await file.ReadAsStreamAsync();

    }
}

but it throws an error here: await Request.Content.ReadAsMultipartAsync(streamProvider);

The error is: Error reading MIME multipart body part. The inner Exception is:

{"Cannot access a disposed object."}

any ideas on why this error is coming up?

TotPeRo
  • 6,293
  • 4
  • 43
  • 57
user441365
  • 3,896
  • 10
  • 40
  • 61

4 Answers4

8

I had a similar problem but the provided solution did not work for me, so here is mine : the file you have uploaded did not match the security limits of IIS.

http://forums.asp.net/t/2062896.aspx?Error+reading+MIME+multipart+body+part+when+upload+image

<system.web>
    <httpRuntime maxRequestLength="30000000" /> <!-- if you forget this one it does not work -->
</system.web>

<system.webServer>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="30000000" />
      </requestFiltering>
    </security>
</system.webServer>
Christophe Blin
  • 1,424
  • 1
  • 17
  • 34
4

I had the same exception, but for a different reason. My Post method had a return type of void. Once I changed the return type to Task<[T]>, type of string in my case, it started working.

Felipe Oriani
  • 36,796
  • 18
  • 129
  • 183
kevinj
  • 51
  • 1
  • 1
    This is the common .NET "async void" problem (i.e you can not have an async method to return void) : https://msdn.microsoft.com/en-us/magazine/jj991977.aspx – Christophe Blin Dec 28 '15 at 10:39
3

Have you tried this?

[HttpPost]
public async Task<IHttpActionResult> Post(string provider)
{  
    if (!Request.Content.IsMimeMultipartContent())
        throw new Exception();

    var streamProvider = await Request.Content.ReadAsMultipartAsync(); // HERE
    foreach (var file in streamProvider.Contents)
    {
        var imageFilename = file.Headers.ContentDisposition.FileName.Trim('\"');
        var imageStream = await file.ReadAsStreamAsync();
    }
}

It looks as it should be called like this.

Carles Company
  • 6,905
  • 5
  • 49
  • 72
-1

Shouldn't you have path to store uploaded files. Something like this:

var streamProvider = new MultipartMemoryStreamProvider(@"C:\Uploads");
buggy08
  • 110
  • 2
  • 9