0

I have a self-hosted webservice that I use with some android apps and it works fine. Now I'm trying to write code in C# to use the same webservices and I've been having problems. Here is the server method I'm trying to access:

[System.ServiceModel.OperationContract, WebInvoke(UriTemplate = "test/")]
string testSaveFile(Stream arq);

public string testSaveFile(Stream img) {
    Console.WriteLine("stream received");
    Console.WriteLine("stream size: " + img.Length); //throws "Error 400 Bad Request"
}

I've tried to access this method by using WebClient.Upload() method, HttpWebRequest with contentType set to multipart/form-data and application/x-www-form-urlencoded and they all return WebException (400) bad request when I try to access the stream. The webservice method do write the first message though, so I can connect to the webservice with no problem. I've tried doing it sync and async, same error. So what is the correct approach to upload data to this method?

Thanks in advance.

jRicardo
  • 804
  • 10
  • 20
  • I haven't worked WCF as much as I should have so I may be wrong, but I'm pretty sure it's just a case of adding a service reference and using the relevant namespaces and methods that will have been automatically generated based on the service. http://msdn.microsoft.com/en-us/library/bb386386.aspx –  Jul 04 '14 at 13:41
  • The problem with that is that I'd have to change endpoints for service reference to be added, and by doing that the webservice would stop to work for my Android Apps... – jRicardo Jul 04 '14 at 13:56
  • I suspect I was barking up the wrong tree based on L.B's answer anyway. –  Jul 04 '14 at 13:59

1 Answers1

2

I tested you code, and it works. The only problem is that your Stream does't support Length property. Change your code similart to this and it will work.

var wc = new WebClient();
var buf = wc.UploadData("http://......./test", new byte[] { 71, 72, 73, 74, 75 });

[OperationContract]
[WebInvoke(ResponseFormat = WebMessageFormat.Json)]
public string testSaveFile(Stream img)
{
    string filename = ".......";
    Console.WriteLine("stream received");
    using (var f = File.OpenWrite(filename))
    {
        img.CopyTo(f);
    }
    Console.WriteLine("stream size: " + new FileInfo(filename).Length);
    return "OK";
}
L.B
  • 114,136
  • 19
  • 178
  • 224
  • Yes, that was it. The length was important to me but I was indeed trying to get it wrong. Thanks – jRicardo Jul 04 '14 at 14:11
  • 1
    @user1531978 you can use `WebOperationContext.Current.IncomingRequest.ContentLength` too, if you are only interested in the length of the stream. – L.B Jul 04 '14 at 14:14