Request.Content.ReadAsMultipartAsync never returns

asp.net-web-api, c#, c#-5.0

Solution

I ran into something similar in .NET 4.0 (no async/await). Using the debugger's Thread stack I could tell that ReadAsMultipartAsync was launching the task onto the same thread, so it would deadlock. I did something like this:

IEnumerable<HttpContent> parts = null;
Task.Factory
    .StartNew(() => parts = Request.Content.ReadAsMultipartAsync().Result.Contents,
        CancellationToken.None,
        TaskCreationOptions.LongRunning, // guarantees separate thread
        TaskScheduler.Default)
    .Wait();

The TaskCreationOptions.LongRunning parameter was key for me because without it, the call would continue to launch the task onto the same thread. You could try using something like the following pseudocode to see if it works for you in C# 5.0:

await TaskEx.Run(async() => await Request.Content.ReadAsMultipartAsync(provider))

Problem

I have an API for a system written using the ASP.NET Web Api and am trying to extend it to allow images to be uploaded. I have done some googling and found how the recommended way to accept files using MultpartMemoryStreamProvider and some async methods but my await on the ReadAsMultipartAsync never returns. Here is the code: ``` [HttpPost] public async Task<HttpResponseMessage> LowResImage(int id) { if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } var provider = new MultipartMemoryStreamProvider(); try { await Request.Content.ReadAsMultipartAsync(provider); foreach (var item in provider.Contents) { if (item.Headers.ContentDisposition.FileName != null) { } } return Request.CreateResponse(HttpStatusCode.OK); } catch (System.Exception e) { return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e); } } ``` I can step through all the way to: ``` await Request.Content.ReadAsMultipartAsync(provider); ``` at which point it will never complete. What is the reason why my await never returns? Update I am attempting to POST to this action using curl, the command is as follows: ``` C:\cURL>curl -i -F filedata=@C:\LowResExample.jpg http://localhost:8000/Api/Photos/89/LowResImage ``` I have also tried using the following html to POST to the action as well and the same thing happens: ``` <form method="POST" action="http://localhost:8000/Api/Photos/89/LowResImage" enctype="multipart/form-data"> <input type="file" name="fileupload"/> <input type="submit" name="submit"/> </form> ```

Original source

Related problems