2014-07-04 21 views
0

我有一个自我托管的web服务,我用一些android应用程序,它工作正常。现在我试图在C#中编写代码来使用相同的Web服务,并且遇到问题。这里是服务器的方法,我试图访问:如何将数据发送到自托管web服务?

[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" 
} 

我试着用WebClient.Upload()方法,用HttpWebRequest的设置的contentType为multipart/form-数据和应用程序访问此方法/ X -www-form-urlencoded,当我尝试访问流时,它们都返回WebException(400)错误的请求。 webservice方法尽管写了第一条消息,所以我可以连接到webservice而没有任何问题。我试过做同步和异步,同样的错误。那么上传数据到这种方法的正确方法是什么?

在此先感谢。

+0

我没有工作WCF,就像我应该有,所以我可能是错的,但我敢肯定它只是增加了服务的参考和使用相关的命名空间的情况下,以及基于服务自动生成的方法。 http://msdn.microsoft.com/en-us/library/bb386386.aspx –

+0

问题是,我不得不改变服务引用的端点被添加,并通过这样做,web服务将停止工作对于我的Android应用程序... – user1531978

+0

我怀疑我根据LB的答案咆哮了错误的树。 –

回答

2

我测试了你的代码,它的工作原理。唯一的问题是,你的不支持长度财产。改变你的代码相似的,它会工作。

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"; 
} 
+0

是的,就是这样。长度对我来说很重要,但我确实想要弄错它。谢谢 – user1531978

+1

@ user1531978如果你只对流的长度感兴趣,你也可以使用'WebOperationContext.Current.IncomingRequest.ContentLength'。 –