Web API POST MultipartFormDataContent: Can response return multipartform content?

Topics: ASP.NET MVC, ASP.NET Web API
Jan 16, 2014 at 9:51 PM
I am trying to send one or more files (.doc) to an ASP.NET Web API 2 service and return a modified version (.docx). I am able to send the file and get a response but the HttpContentMultipartExtensions that I used within the service on the HTTPContent in the request are not available back in the client to use on the response.

Is this something that isn't available out of the box that can be wired up, or is this a misuse of multipartform?

There are two apps: the MVC client and Web API service:

Controller for Client (reads sample files from App_Data, POST to serviceserver/api/mpformdata):
public async Task<ActionResult> PostMpFormData()
{
    DirectoryInfo dir = new DirectoryInfo(Server.MapPath(@"~\App_Data"));
    var files = dir.GetFiles().ToList();

    using (HttpClient client = new HttpClient())
    {
        HttpResponseMessage result = new HttpResponseMessage();
        using (MultipartFormDataContent mpfdc = new MultipartFormDataContent())
        {
            foreach (var file in files)
            {
                mpfdc.Add(new StreamContent(file.OpenRead()), "File", file.Name);
            }

            var requestUri = ConfigurationManager.AppSettings["DocumentConverterUrl"] + "/api/mpformdata";
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("multipart/form-data"));
            result = client.PostAsync(requestUri, mpfdc).Result;
        }

        ViewBag.ResultStatusCode = result.StatusCode;
        ViewBag.ContentLength = result.Content.Headers.ContentLength;

        // Fiddler show that it returns multipartform content, but how do I use it?
        // var resultContent = result.Content;
    }

    return View();
}
Controller for Web API service:
public class UploadController : ApiController
{
    [HttpPost, Route("api/mpformdata")]
    public async Task<HttpResponseMessage> PostMpFormData()
    {
        if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }
        return await UseMultipartFormDataStream();
    }

    private async Task<HttpResponseMessage> UseMultipartFormDataStream()
    {
        string root = HttpContext.Current.Server.MapPath("~/App_Data");
        var provider = new MultipartFormDataStreamProvider(root);
        MultipartFormDataContent mpfdc = new MultipartFormDataContent();

        try
        {
            await Request.Content.ReadAsMultipartAsync(provider);

            foreach (MultipartFileData file in provider.FileData)
            {
                var filename = file.Headers.ContentDisposition.FileName;
                Trace.WriteLine(filename);
                Trace.WriteLine("Server file path: " + file.LocalFileName);
                mpfdc.Add(new ByteArrayContent(File.ReadAllBytes(file.LocalFileName)), "File", filename);
            }
            var response = Request.CreateResponse();    
            response.Content = mpfdc;
            response.StatusCode = HttpStatusCode.OK;
            return response;
        }
        catch (System.Exception e)
        {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
        }
    }
}
Developer
Jan 16, 2014 at 10:05 PM

Multipart extensions are part of System.Net.Http.Formatting dll. Make sure you have the nuget package Microsoft.AspNet.WebApi.Client installed at your client.