Search code examples
c#web-serviceswcffile-uploadself-hosting

How to send data to self-hosted webservice?


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.


Solution

  • 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";
    }