Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7757657
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T13:09:06+00:00 2026-06-01T13:09:06+00:00

Consider a web service written in ASP.NET Web API to accept any number files

  • 0

Consider a web service written in ASP.NET Web API to accept any number files as a ‘multipart/mixed’ request. The helper method mat look as follows (assuming _client is an instance of System.Net.Http.HttpClient):

public T Post<T>(string requestUri, T value, params Stream[] streams)
{
    var requestMessage = new HttpRequestMessage();
    var objectContent = requestMessage.CreateContent(
        value,
        MediaTypeHeaderValue.Parse("application/json"),
        new MediaTypeFormatter[] {new JsonMediaTypeFormatter()},
        new FormatterSelector());

    var content = new MultipartContent();
    content.Add(objectContent);
    foreach (var stream in streams)
    {
        var streamContent = new StreamContent(stream);
        streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        streamContent.Headers.ContentDisposition =
            new ContentDispositionHeaderValue("form-data")
            {
                Name = "file",
                FileName = "mystream.doc"
            };
        content.Add(streamContent);
    }

    return _httpClient.PostAsync(requestUri, content)
        .ContinueWith(t => t.Result.Content.ReadAsAsync<T>()).Unwrap().Result;
}

The method that accepts the request in the subclass of ApiController has a signature as follows:

public HttpResponseMessage Post(HttpRequestMessage request)
{
    /* parse request using MultipartFormDataStreamProvider */
}

Ideally, I’d like to define it like this, where contact, source and target are extracted from the ‘multipart/mixed’ content based on the ‘name’ property of the ‘Content-Disposition’ header.

public HttpResponseMessage Post(Contact contact, Stream source, Stream target)
{
    // process contact, source and target
}

However, with my existing signature, posting the data to the server results in an InvalidOperationException with an error message of:

No ‘MediaTypeFormatter’ is available to read an object of type
‘HttpRequestMessage’ with the media type ‘multipart/mixed’.

There are a number of examples on the internet how to send and receive files using the ASP.NET Web API and HttpClient. However, I have not found any that show how to deal with this problem.

I started looking at implementing a custom MediaTypeFormatter and register it with the global configuration. However, while it is easy to deal with serializing XML and JSON in a custom MediaTypeFormatter, it is unclear how to deal with ‘multipart/mixed’ requests which can pretty much be anything.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-01T13:09:07+00:00Added an answer on June 1, 2026 at 1:09 pm

    Have a look at this forum: http://forums.asp.net/t/1777847.aspx/1?MVC4+Beta+Web+API+and+multipart+form+data

    Here is a snippet of code (posted by imran_ku07) that might help you implement a custom formatter to handle the multipart/form-data:

    public class MultiFormDataMediaTypeFormatter : FormUrlEncodedMediaTypeFormatter
    {
        public MultiFormDataMediaTypeFormatter() : base()
        {
            this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("multipart/form-data"));
        }
    
        protected override bool CanReadType(Type type)
        {
            return true;
        }
    
        protected override bool CanWriteType(Type type)
        {
            return false;
        }
    
        protected override Task<object> OnReadFromStreamAsync(Type type, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext)
        {
            var contents = formatterContext.Request.Content.ReadAsMultipartAsync().Result;
            return Task.Factory.StartNew<object>(() =>
            {
                return new MultiFormKeyValueModel(contents);
            });
        }
    
        class MultiFormKeyValueModel : IKeyValueModel
        {
            IEnumerable<HttpContent> _contents;
            public MultiFormKeyValueModel(IEnumerable<HttpContent> contents)
            {
                _contents = contents;
            }
    
    
            public IEnumerable<string> Keys
            {
                get
                {
                    return _contents.Cast<string>();
                }
            }
    
            public bool TryGetValue(string key, out object value)
            {
                value = _contents.FirstDispositionNameOrDefault(key).ReadAsStringAsync().Result;
                return true;
            }
        }
    }
    

    You then need to add this formatter to your application. If doing self-host you can simply add it by including:

    config.Formatters.Insert(0, new MultiFormDataMediaTypeFormatter());
    

    before instantiating the HttpSelfHostServer class.

    — EDIT —

    To parse binary streams you’ll need another formatter. Here is one that I am using to parse images in one of my work projects.

    class JpegFormatter : MediaTypeFormatter
    {
        protected override bool CanReadType(Type type)
        {
            return (type == typeof(Binary));
        }
    
        protected override bool CanWriteType(Type type)
        {
            return false;
        }
    
        public JpegFormatter()
        {
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("image/jpeg"));
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("image/jpg"));
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("image/png"));
        }
    
        protected override Task<object> OnReadFromStreamAsync(Type type, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext)
        {
            return Task.Factory.StartNew(() =>
                {
                    byte[] fileBytes = new byte[stream.Length];
                    stream.Read(fileBytes, 0, (int)fileBytes.Length);
    
                   return (object)new Binary(fileBytes);
                }); 
        }
    
        protected override Task OnWriteToStreamAsync(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext, TransportContext transportContext)
        {
            throw new NotImplementedException();
        }
    }
    

    In your controller/action you’ll want to do something along the lines of:

    public HttpResponseMessage UploadImage(Binary File) {
     //do something with your file
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Consider an ASP.NET web application [A] that makes a request to a secure web
Consider 3 modules/classes in an ASP.NET Webforms application. I need a web service for
Consider the following .Net ASMX web service with two web methods. using System; using
Consider a standard ASP.NET web application where the user types in some numeric data
I am a complete ASP .NET newbie. I've written a set of web services
I'm designing an API for a web service and I can't decide between using
I'm writing a wrapper class for a third-party web service(SOAP) api. I want to
Often a web service needs to zip up several large files for download by
I am building a web service API, using JSON as the data language. Designing
I am working on a web application (ASP.NET) game that would consist of a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.