Click here to Skip to main content
11,479,951 members (59,937 online)
Click here to Skip to main content

Tagged as

ASP.NET WebApi: MultipartDataMediaFormatter

, 3 Apr 2014 MIT 20.1K 849 9
Rate this:
Please Sign up or sign in to vote.
Used for binding custom types (including files) when sending and receiving multipart encoded form data

Introduction

This is solution for automatic binding action parameters of custom types (including files) encoded as multipart/form-data. It works similar to ASP.NET MVC binding. This media type formatter can be used also for sending objects (using HttpClient) with automatic serialization to multipart/form-data.

This formatter can process:

  • custom non enumarable classes (deep nested classes supported)
  • all simple types that can be converted from/to string (using TypeConverter)
  • files (MultipartDataMediaFormatter.Infrastructure.HttpFile class)
  • generic arrays
  • generic lists
  • generic dictionaries

Using the code

For using this formatter all you need is to simply add current formatter to WebApi Formatters collection:

If WebApi is hosted on IIS (on Application Start):

GlobalConfiguration.Configuration.Formatters.Add(new FormMultipartEncodedMediaTypeFormatter());    

If WebApi is self-hosted:

new HttpSelfHostConfiguration(<url>).Formatters.Add(new FormMultipartEncodedMediaTypeFormatter());      

Using formatter for sending objects (example from test project):

private ApiResult<T> PostModel<T>(T model, string url)
{
 var mediaTypeFormatter = new FormMultipartEncodedMediaTypeFormatter();
 using (new WebApiHttpServer(BaseApiAddress, mediaTypeFormatter))
 using (var client = CreateHttpClient(BaseApiAddress))
 using (HttpResponseMessage response = client.PostAsync(url, model, mediaTypeFormatter).Result)
 {
  if (response.StatusCode != HttpStatusCode.OK)
  {
    var err = response.Content.ReadAsStringAsync().Result;
    Assert.Fail(err);
  }
  
  var resultModel = response.Content.ReadAsAsync<ApiResult<T>>(new[] { mediaTypeFormatter }).Result;
  return resultModel;
  }
}

You can use MultipartDataMediaFormatter.Infrastructure.FormData class to access raw http data:

[HttpPost]
public void PostFileBindRawFormData(MultipartDataMediaFormatter.Infrastructure.FormData formData)
{
      HttpFile file;
      formData.TryGetValue(<key>, out file);
} 

Bind custom model example:

//model example
public class PersonModel
{
   public string FirstName {get; set;}

   public string LastName {get; set;}

   public DateTime? BirthDate {get; set;}

   public MultipartDataMediaFormatter.Infrastructure.HttpFile AvatarImage {get; set;}

   public List<MultipartDataMediaFormatter.Infrastructure.HttpFile> Attachments {get; set;}

   public List<PersonModel> ConnectedPersons {get; set;}
}

//api controller example
[HttpPost]
public void PostPerson(PersonModel model)
{
   //do something with the model
}

History

Version 1.0.1 (2014-04-03)

  • Fixed a bug that caused Exception (No MediaTypeFormatter is available to read an object of type <type name>) when posted data use multipart boundary different from used inside formatter code.
  • Fixed a bug that caused error when binding model with recursive properties.

Version 1.0 (2013-11-22)

  • First release.

License

This article, along with any associated source code and files, is licensed under The MIT License

Share

About the Author

Alexander Kozlovskiy
Software Developer (Senior)
Ukraine Ukraine
.net developer
Follow on   LinkedIn

Comments and Discussions

 
SuggestionMultiple File Upload Supported Now! Pin
Jener Garcia Menezes6-May-15 5:54
memberJener Garcia Menezes6-May-15 5:54 
GeneralRe: Multiple File Upload Supported Now! Pin
Alexander Kozlovskiy7-May-15 5:23
memberAlexander Kozlovskiy7-May-15 5:23 
QuestionThanks Pin
Valdis Iljuconoks10-Mar-15 23:57
memberValdis Iljuconoks10-Mar-15 23:57 
AnswerRe: Thanks Pin
Alexander Kozlovskiy24-Mar-15 0:57
memberAlexander Kozlovskiy24-Mar-15 0:57 
QuestionformData empty Pin
Member 1101580615-Aug-14 19:50
memberMember 1101580615-Aug-14 19:50 
AnswerRe: formData empty Pin
Alexander Kozlovskiy15-Aug-14 20:50
memberAlexander Kozlovskiy15-Aug-14 20:50 
GeneralRe: formData empty Pin
Member 1101580618-Aug-14 4:49
memberMember 1101580618-Aug-14 4:49 
GeneralRe: formData empty Pin
Alexander Kozlovskiy18-Aug-14 8:12
memberAlexander Kozlovskiy18-Aug-14 8:12 
QuestionNuGet Pin
Rory Primrose8-May-14 14:12
memberRory Primrose8-May-14 14:12 
AnswerRe: NuGet Pin
Alexander Kozlovskiy8-May-14 22:30
memberAlexander Kozlovskiy8-May-14 22:30 
GeneralMy vote of 5 Pin
Volynsky Alex4-Apr-14 12:34
professionalVolynsky Alex4-Apr-14 12:34 
GeneralRe: My vote of 5 Pin
Alexander Kozlovskiy5-Apr-14 0:29
memberAlexander Kozlovskiy5-Apr-14 0:29 
GeneralRe: My vote of 5 Pin
Volynsky Alex5-Apr-14 2:55
professionalVolynsky Alex5-Apr-14 2:55 
SuggestionUse MimeMultipartContent Pin
rongchaua1-Mar-14 19:52
memberrongchaua1-Mar-14 19:52 
GeneralRe: Use MimeMultipartContent Pin
mrwizzard5-Jun-14 12:30
membermrwizzard5-Jun-14 12:30 
SuggestionExcellent! Pin
hazal4-Feb-14 8:33
memberhazal4-Feb-14 8:33 
GeneralRe: Excellent! Pin
Alexander Kozlovskiy1-Apr-14 4:01
memberAlexander Kozlovskiy1-Apr-14 4:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150520.1 | Last Updated 3 Apr 2014
Article Copyright 2013 by Alexander Kozlovskiy
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid