【问题标题】:When performing a POST to REST WCF Service get a Unrecognized exception执行 POST 到 REST WCF 服务时出现无法识别的异常
【发布时间】:2013-11-05 06:28:25
【问题描述】:

我有一个 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 类。

我无法成功发布请求。帮助表示赞赏。

【问题讨论】:

    标签: wcf rest wcf-rest


    【解决方案1】:

    我会尝试的第一件事是使用 application/xml 而不是 text/xml

    【讨论】:

      【解决方案2】:

      将您的请求附在肥皂信封中。我DIY了我的请求,当我忘记做必要的事情时出现了这个错误。

      contract-first、javascript、ajax、jquery,都需要你处理细节。就我而言,这很简单,但我挣扎了好几个小时,却没有看到明显的东西。

      【讨论】:

        【解决方案3】:

        我终于找到了异常的根本原因。以下代码完美运行:

        var client = new RestClient();
        client.BaseUrl = serviceBaseUrl;
        var request = new RestRequest(method){RequestFormat = DataFormat.Xml};
        request.Resource = resourceUrl;
        request.AddParameter("text/xml",requestBody, ParameterType.RequestBody);
        var response = client.Execute(request);
        

        作为参数发送的 requestBody 应该是一个序列化的 xmlString。

        注意:如果 REST 服务上公开的复合类型使用 DataContractSerializer,请确保使用 DataContractSerializer 生成 requestBody,如果使用 XmlSerializer,则使用 XmlSerializer 生成 requestBody。

        【讨论】:

          猜你喜欢
          • 2010-12-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多