Multipart form POST using ASP.Net Web API

后端 未结 2 1272
说谎
说谎 2020-12-15 10:56

I have a POST ASP.Net Web Api method adapted from A guide to asynchronous file uploads in ASP.NET Web API RTM.

I am running into faulted Task problem with all the re

相关标签:
2条回答
  • 2020-12-15 11:54

    It turns out, as Filip suggested in the comments, that the Web API Usage Handler that I adapted from Implementing Message Handlers To Track Your ASP .net Web API Usage was reading the content body and hence messing with the position seeker on the stream when the request was being processed in my POST method.

    So, I added a conditional statement to the WebApiUsageHandler to not read the request body if the request is of type IsMimeMultipartContent. This fixed the problem.

    Update

    I want to update the answer with another option, suggested to me by Filip via email, so that it is documented:

    If you use this code inside the API usage handler, just before reading the body:

       //read content into a buffer
       request.Content.LoadIntoBufferAsync().Wait();
    
       request.Content.ReadAsStringAsync().ContinueWith(t =>
       {
           apiRequest.Content = t.Result;
           _repo.Add(apiRequest);
       });
    

    The request will be buffered and will be possible to read it twice, and therefore the upload will be possible further down the pipeline. Hope this helps.

    0 讨论(0)
  • 2020-12-15 11:57

    This is not an answer to the original poster's question. However, calling the ReadAsMultipartAsync() method more than one time in my codes also caused the same exception:

    public async Task<IHttpActionResult> PostFiles()
    {
    
         // Check if the request contains multipart/form-data.
         if (!Request.Content.IsMimeMultipartContent())
         {
             return Content(HttpStatusCode.BadRequest, "Unsupported media type. ";
        }
         try
         {
            var provider = new CustomMultipartFormDataStreamProvider(workingFolder);
    
            await Request.Content.ReadAsMultipartAsync(provider); // OK
            await Request.Content.ReadAsMultipartAsync(provider); // calling it the second time causes runtime exception "Unexpected end of MIME multipart stream. MIME multipart message is not complete"
            ... 
    
        }
        catch(Exception ex)
        {
            ...
        }
    }
    
    0 讨论(0)
提交回复
热议问题