RESTful WCF service image upload problem

1 namespace Uploader  
2 {  
3     using System;  
4     using System.IO;  
5     using System.ServiceModel;  
6     using System.ServiceModel.Description;  
7     using System.ServiceModel.Web;  
8     using System.Drawing;  
9     using System.Drawing.Imaging;  
10     using System.Net;  
11     using System.Xml;  
13     [ServiceContract(Namespace = "http://Uploader")]  
14     public interface IUploaderService  
15     {  
16         [OperationContract, WebInvoke(Method = "POST",UriTemplate = "File/{fileName}")]  
17         bool UploadFile(string fileName, Stream fileContents);  
18     }  
20     [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]  
21     public class UploaderService : IUploaderService  
22     {  
23         public bool UploadFile(string fileName, Stream fileContents)  
24         {  
25             return true;  
26         }  
27     }  
29     class Program  
30     {  
31         static void Main()  
32         {  
33             var host = new   
34                 ServiceHost(typeof (UploaderService),   
35                 new Uri("http://localhost:8080/Uploader"));  
36             host.AddServiceEndpoint("Uploader.IUploaderService",   
37                 new WebHttpBinding(), "").Behaviors.Add(new WebHttpBehavior());  
38             try  
39             {  
40                 host.Open();  
41                 Console.WriteLine(host.BaseAddresses[0].AbsoluteUri + " running.");  
42                 Console.WriteLine();  
43                 var uri = "http://localhost:8080/Uploader/file.jpg";  
44                 var req = WebRequest.Create(uri) as HttpWebRequest;  
45                 if (req != null)  
46                 {  
47                     req.Method = "POST";  
48                     req.ContentType = "image/jpeg";  
49                     var reqStream = req.GetRequestStream();  
51                     var imageStream = new MemoryStream();  
52                     using (var i = Image.FromFile(@"c:\photo.jpg"))   
53                         i.Save(imageStream, ImageFormat.Jpeg);  
55                     var imageArray = imageStream.ToArray();  
56                     reqStream.Write(imageArray, 0, imageArray.Length);  
57                     reqStream.Close();  
58                     var resp = (HttpWebResponse)req.GetResponse();  
59                     var r = new XmlTextReader(resp.GetResponseStream());  
60                     if (r.Read())  
61                     {  
62                         Console.WriteLine(r.ReadString());      
63                     }  
64                 }  
65                 Console.WriteLine("Press <ENTER> to quit.");  
66                 Console.ReadLine();  
67             }  
68             catch (Exception ex)  
69             {  
70                 Console.WriteLine(ex.Message);  
71                 Console.ReadKey();  
72             }  
73             finally  
74             {  
75                 if (host.State == CommunicationState.Faulted)  
76                     host.Abort();  
77                 else  
78                     host.Close();  
79             }  
80         }  
81     }  
82 }  

Hi, hope you can help....

I am creating a simple app(maybe webpage) that will have a simple UI and will upload files from an external device, the app/webpage will be started via autorun.inf when the user plugs a device into there PC. The webservice will perform the complex job of linking the file to the management system etc. This will enable the IT illiterate users that can't use file explore to submit files to the the management system...!

The problem I have is that my RESTful serivce is giving me a 400 error when the content type is a image/jpeg.. It works fine for text/plain or text/xml (see Blog Post)

Thanks J

2009-03-20 01:42:07 Scores:6

1 answer

Answer 1

You can try to override any content-type and upload all files as application/octet-stream, or text/plain using an IOperationBehavior.

public class WebContentTypeAttribute : Attribute, IOperationBehavior, IDispatchMessageFormatter
    private IDispatchMessageFormatter innerFormatter;
    public string ContentTypeOverride { get; set; }

    public WebContentTypeAttribute(string contentTypeOverride)
        this.ContentTypeOverride = contentTypeOverride;

    // IOperationBehavior
    public void Validate(OperationDescription operationDescription)


    public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
        innerFormatter = dispatchOperation.Formatter;
        dispatchOperation.Formatter = this;

    public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)


    public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters)


    // IDispatchMessageFormatter
    public void DeserializeRequest(Message message, object[] parameters)
        if (message == null)

        if (string.IsNullOrEmpty(ContentTypeOverride))

        var httpRequest = (HttpRequestMessageProperty)message.Properties[HttpRequestMessageProperty.Name];
        httpRequest.Headers["Content-Type"] = ContentTypeOverride;

    public Message SerializeReply(MessageVersion messageVersion, object[] parameters, object result)
        return innerFormatter.SerializeReply(messageVersion, parameters, result);

And you would have to modify your Service contract to look like this one

[WebInvoke(Method = "POST",UriTemplate = "File/{fileName}")]
bool UploadFile(string fileName, Stream fileContents);

Although, if you are uploading from a webpage, wouldn't the data be posted in a multipart/form-data format?

bendewey H
2009-03-20 02:48:10
Just what I was after! Not sure about the the webpage upload yet, however I may use JavaScript to hook into the service, so I will need to make a JSON enabled version too. Cross that bridge when/if i reach it. The app is a small protoype at the mo.
jaimie H
2009-03-20 14:37:16 Scores:0
I'm really liking this RESTful WCF, it seems so much cleaner and thinner than the standard SOAP WS-* standards for interoperability. There is a great white paper on msdn: for anyone who wants to know more. Thanks for your help Ben... J
jaimie H
2009-03-20 14:37:58 Scores:2
Share |
View original post at

Related topics

Problem with POST request to RESTful WCF Service

I am trying to make a post request to my restful WCF service. The contract looks like this: [OperationContract] [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ...

Upload Image From iPhone to WCF Service

I'm trying to build an iPhone app and c# WCF Service to upload an image to a SQL Service database. I've got my app breaking an image down to NSData and posting off to a WCF Service using the following code: NSData *imageData = UIImageJPEGRepresentation(self.image, 90); NSURL *url = [NSURL URLWithString:@""]; ASIFormDataRequest *request = ...

RESTful WCF web service POST problem

I can't pass over parameters to wcf web service. My web method: [OperationContract] [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, UriTemplate = "playersJson2")] List<Person> GetPlayers(string name1, string name2); When ...

Uploading image as attachment in RESTful WCF Service

I am trying to upload an image as an attachment in REST WCF Service and I am getting the following error. "Access to path "C:\ImageUpload" is denied" I have enabled Full Contorl permissions to this folder. I dont understand why I am getting this error. I am new to WCF, and the most ...

Returning an image from a RESTful WCF service

I have this very simple DTO: [DataContract] public class DTO { [DataMember] public byte[] Image {get; set; } } And this very simple service: [ServiceContract] public interface IFooService { [WebGet( UriTemplate = "", RequestFormat ...

Upload image to the server without file upload control

Am currenty working on writing code in c# to handle some operation for our iphone app.These code files will be in our server and the url are used by iPhone team to call those specific files and ger their values. Now am working on photo upload functionality.I have no idea how ...

Exception: Could not find default endpoint element when call Bing translate service from RESTFUL service

I'm building a RESTFUL webservice and a consoleHost application to host that webservice. In RESTFUL webservice, I call BingTranslate service (link reference to: My service host successfully, but when I call function that call the BingTranslate service, this exception thrown: "Could not find default endpoint element that references contract 'BingTranslator.LanguageService' ...

can i upload a user-selected image to server using web service?

I am doing a ASP .NET website where among other things a user can upload an image, that needs to be saved to the server. In the whole website I'm trying to accomplish as minimal communication between the client and server as possible. This means that on onload() I invoke ...

Android post byte array(image) to WCF restful service

I have a WCF service that I am able to post strings to with no problem but now I'm trying to post a byte array as a string and this is where I am getting issues. My goal is to take a picture, convert it to a byte(), send that ...

WCF Restful service file upload with multi-platform support

can anybody please tell me how can i create a WCF Rest service through which i can be abel to upload files to server using android , iphone & WP7. ...