0

我正在编写一个示例 WCF Restful 服务。这是尝试将对象传递给服务中的 POST 方法。这是代码

客户端代码:

HttpWebRequest req = null;
HttpWebResponse res = null;
string serviceurl = "localhost:63004/MySampleService.svc/Survey";
string XmlText;
req = (HttpWebRequest)WebRequest.Create(serviceurl);
req.Method = "POST";
req.ContentType = "application/xml; charset=utf-8";
req.Timeout = 30000;
req.Headers.Add(serviceurl);

var xmlDoc = new XmlDocument { XmlResolver = null };
xmlDoc.Load(Server.MapPath("Sample.xml"));
string sXml = xmlDoc.InnerXml;
req.ContentLength = sXml.Length;
var sw = new StreamWriter(req.GetRequestStream());
sw.Write(sXml);
sw.Close();

res = (HttpWebResponse)req.GetResponse();  //GETTING THE BAD REQUEST(400) ERROR here.

服务代码:

[OperationContract]
[WebInvoke(UriTemplate = "/Survey", Method = "POST", RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped)]
void InsertData(Survey SurveyItem);

任何人都可以帮助我......提前谢谢......

4

1 回答 1

0

您尚未在 web.config 或 app.config 中为 wcf 服务提供有关配置的详细信息。但是我在您的 webinvoke 属性中发现了一个错误。

每当您像上面那样发布请求(将 xml 直接作为字符串)时,您必须将 bodystyle 参数设置为 Bare,如下面的代码片段所示。

[OperationContract]
[WebInvoke(UriTemplate = "/Survey", Method = "POST", RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Bare)]
void InsertData(Survey SurveyItem);
于 2013-04-24T07:38:31.107 回答