2011-03-27 50 views
2

如何获取HTTP POST请求中的数据,该数据在我的WCF服务中收到?提取HTTP POST数据(WCF C#)

我使用HTTP POST从其他服务发送的数据:

 string ReportText = "Hello world"; 

     ASCIIEncoding encoding = new ASCIIEncoding(); 
     byte[] data = encoding.GetBytes(ReportText); 

     // Prepare web request... 
     String serverURL = ConfigurationManager.AppSettings["REPORT"]; 
     HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serverURL); 
     myRequest.Method = "POST"; 
     myRequest.ContentType = "application/x-www-form-urlencoded"; 
     myRequest.ContentLength = data.Length; 
     Stream newStream = myRequest.GetRequestStream(); 

     // Send the data. 
     newStream.Write(data, 0, data.Length); 
     newStream.Close(); 

,但是当我在WCF收到POST请求使用WebOperationContext.Current.IncomingRequest, 我不能找到一种方法来提取它我如何从HTTP POST请求中提取数据?

+0

什么是你为了支持'应用/在你的WCF服务的X WWW的形式urlencoded'使用绑定? – 2011-03-27 09:03:51

+0

你可以发布你的服务代码的样子吗?它看起来并不像你连接到WCF,而只是做一个标准的HTTP请求。 – Tridus 2011-03-27 11:43:49

+0

@tridus - 发送POST请求的客户端将其作为标准HTTP POST发送,而不是从WCF发送。我如何从我的WCF中提取发送像上面的示例一样的POST数据? (链接,代码示例...) – Rodniko 2011-03-29 14:55:47

回答

0

Hello world并不完全是application/x-www-form-urlencoded。您需要相应地编码邮件正文someproperty=Hello%20world以及使用WCF HTTP绑定。

+0

谢谢,你能解释多一点...你有一个代码示例?... – Rodniko 2011-03-29 15:00:30

5

我的猜测是,你正在使用WCF REST服务,你可以拉GET参数,但你无法读取RAW数据后?

如果是这种情况,请在Contract声明的参数列表末尾添加Stream参数。如果函数末尾有单个流,则框架将其视为原始数据流。

  [OperationContract] 
      [WebInvoke(Method = "POST", UriTemplate = "DoSomething?siteId={siteId}&configTarget={configTarget}", 
      RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] 
      bool DoSomething(string itemid, Stream body); 


    public bool DoSomething(int siteId, string configTarget, Stream postData) 
    { 
     string data = new StreamReader(postData).ReadToEnd(); 
     return data.Length > 0; 
    } 

请参阅此链接了解详情: http://blogs.msdn.com/b/carlosfigueira/archive/2008/04/17/wcf-raw-programming-model-receiving-arbitrary-data.aspx

+0

谢谢詹姆斯,你的文章帮助我解决了我的问题。我正在尝试创建Rest WCF服务,它将以内容类型'application/x-www-form-urlencoded'和数据在请求正文中发布为'key = value&key = value .....'。为了让我的应用程序与第三方服务集成(这将使用所有这些规范调用我的服务),我一直在努力争取这个结构。 – Shaggy 2017-03-16 12:21:31