HTTP POST到WCF服务

我试图通过HTTP POST调用WCF服务,但该服务返回400错误。 我不知道这是由于OperationContract还是我正在进行POST的方式。 这是合同在服务器端的样子:

[OperationContract, WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped)] Stream Download(string username, int fileid); 

以下是我试图通过测试控制台应用程序调用服务的方法:

 HttpWebRequest webRequest = WebRequest.Create("http://localhost:8000/File/Download") as HttpWebRequest; webRequest.Method = "POST"; webRequest.ContentType = "application/x-www-form-urlencoded"; byte[] bytes = Encoding.ASCII.GetBytes("username=test&fileid=1"); Stream os = null; webRequest.ContentLength = bytes.Length; os = webRequest.GetRequestStream(); os.Write(bytes, 0, bytes.Length); os.Close(); WebResponse webResponse = webRequest.GetResponse(); 

编辑:我应该说清楚我的目标是测试服务,而不是让它接受原始的HTTP POST。 如果有更好的方法可以测试服务,请随时分享。

如果您能够使用其他内容类型,则可以使用json,它将在您的示例中使用。

更改

 webRequest.ContentType = "application/x-www-form-urlencoded"; byte[] bytes = Encoding.ASCII.GetBytes("username=test&fileid=1"); 

 webRequest.ContentType = "application/json"; byte[] bytes = Encoding.ASCII.GetBytes("{\"username\":\"test\",\"fileid\":1"); 

如果您必须使用application / x-www-form-urlencoded内容类型,请google wcf application / x-www-form-urlencoded以获取几个post以及描述解决方法的其他SO问题。

这是一个非常简单的过程,但不容易访问或直接(不幸的是WCF的许多方面的情况)请查看这篇文章以获得澄清:

服务合约:

 [ServiceContract] public interface ISampleService { [OperationContract] [WebInvoke(UriTemplate = "invoke")] void DoWork(Stream input); } 

HTML源代码:

 
:

:

代码背后:

 public void DoWork(Stream input) { StreamReader sr = new StreamReader(input); string s = sr.ReadToEnd(); sr.Dispose(); NameValueCollection qs = HttpUtility.ParseQueryString(s); string firstName = qs["firstName"]; string lastName = qs["lastName"]; }