REST WCF中的POST请求

时间:2014-03-25 04:44:35

标签: wcf rest

我开发了一个REST WCF服务方法如下:

 [OperationContract]
    [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml, UriTemplate = "/Details")]
    DetailData GetDetails(TestData requst);


 [DataContract]
public class TestData
{
    [DataMember]
    public string DetailData { get; set; }
}

现在我尝试使用以下客户端代码调用服务:

  ASCIIEncoding encoding = new ASCIIEncoding();
  string testXml = "<TestData>" +
                      "<DetailData>" +
                          "4000" +
                       "</DetailData>" +
                    "</TestData>";

 string postData = testXml.ToString();
 byte[] data = encoding.GetBytes(postData);
 string url = "http://localhost/WCFRestService.svc/bh/Details";
 string strResult = string.Empty;

 // declare httpwebrequet wrt url defined above
 HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
 // set method as post
 webrequest.Method = "POST";
 // set content type
 webrequest.ContentType = "text/xml";
 // set content length
 webrequest.ContentLength = data.Length;
 // get stream data out of webrequest object
 Stream newStream = webrequest.GetRequestStream();
 newStream.Write(data, 0, data.Length);
 newStream.Close();

 //Gets the response
 WebResponse response = webrequest.GetResponse();
 //Writes the Response
 Stream responseStream = response.GetResponseStream();

 StreamReader sr = new StreamReader(responseStream);
 string s = sr.ReadToEnd();

我收到以下错误:

&#34;远程服务器返回错误:(400)错误请求&#34;

我可以成功调用另一种服务方法,其中&#34; GET&#34;正在使用动词。但是上面用于使用&#34; POST&#34;来调用服务的客户端代码动词不起作用。我想,我在客户端代码中遗漏了一些东西。 可能是什么问题?

1 个答案:

答案 0 :(得分:0)

尝试更改

WebMessageBodyStyle.WrappedRequest

WebMessageBodyStyle.Bare