title: Web API Model Binding with Multipart formdata
body: <p>Is there a way to be able to get model binding (or whatever) to give out the model from a multipart form data request in <strong>ASP.NET MVC Web API</strong>?</p>
  
  <p>I see various blog posts but either things have changed between the post and actual release or they don't show model binding working.</p>
  
  <p>This is an outdated post: <a href="http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-2">Sending HTML Form Data</a></p>
  
  <p>and so is this: <a href="http://blogs.msdn.com/b/henrikn/archive/2012/03/01/file-upload-and-asp-net-web-api.aspx">Asynchronous File Upload using ASP.NET Web API</a></p>
  
  <p>I found this code (and modified a bit) somewhere which reads the values manually:</p>
  
  <p><strong>Model:</strong></p>
  
  <pre><code>public class TestModel
  {
      [Required]
      public byte[] Stream { get; set; }
  
      [Required]
      public string MimeType { get; set; }
  }
  </code></pre>
  
  <p><strong>Controller:</strong></p>
  
  <pre><code>    public HttpResponseMessage Post()
      {
          if (!Request.Content.IsMimeMultipartContent("form-data"))
          {
              throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
          }
  
          IEnumerable&lt;HttpContent&gt; parts = Request.Content.ReadAsMultipartAsync().Result.Contents;
  
  
          string mimeType;
          if (!parts.TryGetFormFieldValue("mimeType", out mimeType))
          {
              return Request.CreateResponse(HttpStatusCode.BadRequest);
          }
  
          var media = parts.ToArray()[1].ReadAsByteArrayAsync().Result;
  
          // create the model here
          var model = new TestModel()
              {
                  MimeType = mimeType,
                  Stream = media
              };
          // save the model or do something with it
          // repository.Save(model)
  
          return Request.CreateResponse(HttpStatusCode.OK);
      }
  </code></pre>
  
  <p><strong>Test:</strong></p>
  
  <pre><code>[DeploymentItem("test_sound.aac")]
  [TestMethod]
  public void CanPostMultiPartData()
  {
      var content = new MultipartFormDataContent { { new StringContent("audio/aac"),  "mimeType"}, new ByteArrayContent(File.ReadAllBytes("test_sound.aac")) };
  
      this.controller.Request = new HttpRequestMessage {Content = content};
      var response = this.controller.Post();
  
      Assert.AreEqual(response.StatusCode, HttpStatusCode.OK);
  }
  </code></pre>
  
  <p>This code is basically fragile, un-maintainable and further, doesn't enforce the model binding or data annotation constraints. </p>
  
  <p>Is there a better way to do this?</p>
  
  <p><strong>Update:</strong> I've seen this <a href="http://byterot.blogspot.com/2012/04/aspnet-web-api-series-part-5.html">post</a> and this makes me think - do I have to write a new formatter for every single model that I want to support?</p>