【问题标题】:WCF Restful services getting error 400 (bad request) when post xml dataWCF Restful 服务在发布 xml 数据时收到错误 400(错误请求)
【发布时间】:2011-03-04 06:09:45
【问题描述】:

我正在尝试自行托管 WCF 服务并通过 javascript 调用服务。当我通过 Json 而不是 xml(400 错误请求)传递请求数据时,它可以工作。请帮忙。

合同:

public interface iSelfHostServices
{

    [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = INFOMATO.RestTemplate.hello_post2,RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped)]
    Stream hello_post2(string helloString);

}

服务器端代码:

public Stream hello_post2(string helloString)
{
    if (helloString == null)
    {
        WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.BadRequest;
        return null;
    }
    WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;
    return new MemoryStream(Encoding.UTF8.GetBytes(helloString));

}

JavaScript:

function testSelfHost_WCFService_post_Parameter() {

   var xmlString = "<helloString>'hello via Post'</helloString>";
   Ajax_sendData("hello/post2", xmlString);
}

function Ajax_sendData(url, data) {
   var request = false;
   request = getHTTPObject();
   if (request) {
       request.onreadystatechange = function() {
       parseResponse(request);
       };

       request.open("post", url, true);
       request.setRequestHeader("Content-Type", "text/xml; charset=utf-8"); charset=utf-8"); 
       request.send(data);
       return true;
   }
}

function getHTTPObject() {
   var xhr = false;
   if (window.XMLHttpRequest) {
      xhr = new XMLHttpRequest();
      } else if (window.ActiveXObject) {...}
}

【问题讨论】:

    标签: xml wcf rest post xmlhttprequest


    【解决方案1】:

    这是因为 WCF 期望您传递的字符串使用 Microsoft 序列化命名空间进行序列化。如果您发送,

    <string xmlns='http://schemas.microsoft.com/2003/10/Serialization/'>hello via Post</string>
    

    那么它可能会正确反序列化。

    【讨论】:

    • 达雷尔,谢谢。我试过你的建议。但我仍然得到相同的错误代码 400。由于某些原因,如果我通过 xml 传递任何参数,服务无法识别该函数。如果我修改了函数以使不传递任何参数,则成功调用了该函数。还有其他建议吗?
    • @Wayne 尝试将字符串放入 CDATA 部分。
    【解决方案2】:

    您需要在 WebInvoke 属性中将 body 样式设置为 Bare,如下面的 sn-p 所示,同时发送您在上面发送的 XML 标签。

    [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = INFOMATO.RestTemplate.hello_post2,RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Bare)]
    Stream hello_post2(string helloString);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-27
      • 2015-11-24
      • 1970-01-01
      • 1970-01-01
      • 2011-09-29
      • 2014-01-11
      • 1970-01-01
      相关资源
      最近更新 更多