WCF service to accept a post encoded multipart/form-data

Does anyone know, or better yet have an example, of a WCF service that will accept a form post encoded multipart/form-data ie. a file upload from a web page?

I have come up empty on google.

Ta, Ant

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

So, here goes…

Create your service contract which an operation which accepts a stream for its only parameter, decorate with WebInvoke as below

public interface IService1 {

        Method = "POST",
        BodyStyle = WebMessageBodyStyle.Bare,
        UriTemplate = "/Upload")]
    void Upload(Stream data);


Create the class…

    public class Service1 : IService1 {

    public void Upload(Stream data) {

        // Get header info from WebOperationContext.Current.IncomingRequest.Headers
        // open and decode the multipart data, save to the desired place

And the config, to accept streamed data, and the maximum size

       <binding name="WebConfiguration" 
       <behavior name="WebBehavior">
         <webHttp />         
       <behavior name="Sandbox.WCFUpload.Web.Service1Behavior">
         <serviceMetadata httpGetEnabled="true" httpGetUrl="" />
         <serviceDebug includeExceptionDetailInFaults="false" />
     <service name="Sandbox.WCFUpload.Web.Service1" behaviorConfiguration="Sandbox.WCFUpload.Web.Service1Behavior">
        contract="Sandbox.WCFUpload.Web.IService1" />

Also in the System.Web increase the amount of data allowed in System.Web

        <httpRuntime maxRequestLength="2000000"/>

This is just the basics, but allows for the addition of a Progress method to show an ajax progress bar and you may want to add some security.

Solution 2

I don’t exactly know what you’re trying to accomplish here, but there’s no built-in support in “classic” SOAP-based WCF to capture and handle form post data. You’ll have to do that yourself.

On the other hand, if you’re talking about REST-based WCF with the webHttpBinding, you could certainly have a service methods that is decorated with the [WebInvoke()] attribute which would be called with a HTTP POST method.

    [WebInvoke(Method="POST", UriTemplate="....")]
    public string PostHandler(int value)

The URI template would define the URI to use where the HTTP POST should go. You’d have to hook that up to your ASP.NET form (or whatever you’re using to actually do the post).

For a great introduction to REST style WCF, check out Aaron Skonnard’s screen cast series on the WCF REST Starter Kit and how to use it.


Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply