2011-06-21 57 views
0

我有一个WCF REST服务,并试图手动发布一些数据给它,以便WCF方法得到它作为它的参数,但遇到问题在POST c#中填充变量的位置。 WCF的方法是:如何使用c#发送POST变量?

[OperationContract] 
[WebInvoke] 
string EchoWithPost(string message); 

到目前为止我已经采取了一些脚本关闭MSDN网站:

  // Create a request using a URL that can receive a post. 
      WebRequest request = WebRequest.Create("http://localhost:52587/VLSContentService.svc/rest/EchoWithGet/Hello%20World"); 
      // Set the Method property of the request to POST. 
      request.Method = "POST"; 
      // Create POST data and convert it to a byte array. 
      string postData = "This is a test that posts this string to a Web server."; 
      byte[] byteArray = Encoding.UTF8.GetBytes(postData); 
      // Set the ContentType property of the WebRequest. 
      request.ContentType = "application/x-www-form-urlencoded"; 
      // Set the ContentLength property of the WebRequest. 
      request.ContentLength = byteArray.Length; 
      // Get the request stream. 
      Stream dataStream = request.GetRequestStream(); 
      // Write the data to the request stream. 
      dataStream.Write(byteArray, 0, byteArray.Length); 
      // Close the Stream object. 
      dataStream.Close(); 
      // Get the response. 
      WebResponse response = request.GetResponse(); 
      // Display the status. 
      Console.WriteLine(((HttpWebResponse)response).StatusDescription); 
      // Get the stream containing content returned by the server. 
      dataStream = response.GetResponseStream(); 
      // Open the stream using a StreamReader for easy access. 
      StreamReader reader = new StreamReader(dataStream); 
      // Read the content. 
      string responseFromServer = reader.ReadToEnd(); 
      // Display the content. 
      Console.WriteLine(responseFromServer); 
      // Clean up the streams. 
      reader.Close(); 
      dataStream.Close(); 
      response.Close(); 

林真的不知道如何将脚本转换成一些代码,将发布“信息”到WCF服务。任何人都可以帮忙吗?

回答

1

WCF REST端点默认理解两种数据:XML和JSON,所以下面所示的两种方式应该可以正常工作,因为运作需要一个string

string postData = "\"This is a test that posts this string to a Web server.\""; 
byte[] byteArray = Encoding.UTF8.GetBytes(postData); 
request.ContentType = "application/json; 

string postData = "<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">This is a test that posts this string to a Web server.</string>"; 
byte[] byteArray = Encoding.UTF8.GetBytes(postData); 
request.ContentType = "text/xml; 

WCF不支持内容类型的应用程序/ x-www-form-urlencoded(但是如果从http://wcf.codeplex.com/获得“jQuery支持”,则可以找到支持它的行为)。如果你想接收任何类型的数据,包括非结构化数据(如纯文本),你可以在http://blogs.msdn.com/b/carlosfigueira/archive/2008/04/17/wcf-raw-programming-model-receiving-arbitrary-data.aspx找到更多信息。

1

我相信正确的Postdata会是message=YOUR_ESCAPED_POSTDATA&additional=arguments,就像GET查询的样子。

你可以下载一个像firebug这样的插件并提交一个常规表单。然后,您可以看到浏览器如何发送其后数据并将其复制。