使用POST方法的WCF Restful Services将BAD REQUEST(400)返回给响应对象

时间:2013-04-23 11:02:34

标签: wcf-rest wcf-endpoint

我正在编写一个示例WCF Restful Service。这里是尝试将对象传递给服务中的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);

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

1 个答案:

答案 0 :(得分:0)

您尚未提供有关wcf服务的web.config或app.config中的配置的详细信息。但我发现你的webinvoke属性有一个问题。

每当您发布上述请求(Direct xml as string)时,您必须将bodystyle参数设置为Bare,如下面的代码片段所示。

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