Skip to content

Instantly share code, notes, and snippets.

@tuespetre
Last active August 29, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tuespetre/9449b7310f6519368883 to your computer and use it in GitHub Desktop.
Save tuespetre/9449b7310f6519368883 to your computer and use it in GitHub Desktop.
For use with pre-MVC6 Web API controllers
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.ValueProviders;
public class MultipartFormDataValueProvider : IValueProvider
{
private HttpActionContext actionContext = null;
private IEnumerable<HttpContent> multipartContents;
private IEnumerable<HttpContent> MultipartContents
{
get
{
if (multipartContents == null)
{
var task = actionContext.Request.Content.ReadAsMultipartAsync();
task.Wait();
multipartContents = task.Result.Contents;
}
return multipartContents;
}
}
public MultipartFormDataValueProvider(HttpActionContext actionContext)
{
this.actionContext = actionContext;
}
public bool ContainsPrefix(string prefix)
{
throw new NotImplementedException();
}
public ValueProviderResult GetValue(string key)
{
var item = MultipartContents.FirstOrDefault(c => c.Headers.ContentDisposition.Name.Trim('"') == key);
if (item == null)
{
return null;
}
var task = item.ReadAsStringAsync();
task.Wait();
return new ValueProviderResult(
rawValue: task.Result,
attemptedValue: task.Result,
culture: CultureInfo.InvariantCulture);
}
}
public class MultipartFormDataValueProviderFactory : ValueProviderFactory
{
public override IValueProvider GetValueProvider(HttpActionContext context)
{
return new MultipartFormDataValueProvider(context);
}
}

You need to register the factory in Startup.cs:

GlobalConfiguration.Configure(config =>
{
    config.Services.Add(typeof(ValueProviderFactory), new MultipartFormDataValueProviderFactory());
}); 

That should take care of complex type arguments on your API controllers. For simple types you have to specify the [ModelBinder] attribute on the parameter.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment