执行 POST 到 REST WCF 服务时出现无法识别的异常
我有一个 REST POST 方法,如下所示:
[WebInvoke(BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Xml, RequestFormat = WebMessageFormat.Xml)]
string GetFromXml(XElement xmlString);
我正在尝试使用以下代码从我的客户端执行后操作:
var client = new RestClient();
client.BaseUrl = "http://localhost/XMLRestService/XmlService.svc";
var request = new RestRequest(Method.POST);
request.Resource = "GetFromXml";
client.AddDefaultHeader("Content-Type", "text/xml");
request.AddBody(obj, "XMLRestService");
var response = client.Execute(request);
当我执行上述操作时,我收到 400 Bad 请求。然后我在 WCF 服务上启用了跟踪。堆栈跟踪给了我一个无法识别的消息版本异常,该异常被抛出我的 System.ServiceModel.CommunicationException 类。
我无法成功发布请求。帮助表示赞赏。
I have a REST POST method as follows:
[WebInvoke(BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Xml, RequestFormat = WebMessageFormat.Xml)]
string GetFromXml(XElement xmlString);
I am trying to do a post operation from my client using the following code:
var client = new RestClient();
client.BaseUrl = "http://localhost/XMLRestService/XmlService.svc";
var request = new RestRequest(Method.POST);
request.Resource = "GetFromXml";
client.AddDefaultHeader("Content-Type", "text/xml");
request.AddBody(obj, "XMLRestService");
var response = client.Execute(request);
When i do the above i get a 400 Bad request. I then enabled tracing on the WCF Service. And the stack trace gave me a Unrecognized Message version excpetion that is thrown my the System.ServiceModel.CommunicationException
class.
I am unable to post the request successfully. Help appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我要尝试的第一件事是使用 application/xml 而不是 text/xml
The first thing I would try is using application/xml instead of text/xml
将您的请求放入肥皂信封中。我DIY了我的请求,当我忘记做需要的事情时,我得到了这个错误。
契约优先、javascript、ajax、jquery,都需要你处理细节。对我来说这是理所当然的事,但我挣扎了几个小时却没有看到明显的情况。
enclose your request in a soap envelope. I DIY my requests and I got this error when I forgot to do the needful.
contract-first, javascript, ajax, jquery, all require you handle the details. Such a no brainer on my part, but I struggled for hours w/o seeing the obvious.
我终于找到了异常的根本原因。下面的代码工作完美:
作为参数发送的 requestBody 应该是序列化的 xmlString。
注意:如果 REST 服务上公开的复合类型使用 DataContractSerializer,则确保使用 DataContractSerializer 生成 requestBody,如果使用 XmlSerializer,则使用 XmlSerializer 生成 requestBody。
I finally found the root cause to the exception. The below code works perfect:
The requestBody being sent as parameter should be a serialized xmlString.
NOTE: If the composite type exposed on the REST Service is using DataContractSerializer then make sure to generate the requestBody using DataContractSerializer and if uses XmlSerializer then generate the requestBody using XmlSerializer.