WCF Restful服务获取错误400(错误的请求)时发布xml数据

WCF Restful服务获取错误400(错误的请求)时发布xml数据

问题描述:

我想自己承载一个WCF服务并通过JavaScript调用服务。当我通过Json传递请求数据而不是xml(400错误请求)时它工作。请帮忙。WCF Restful服务获取错误400(错误的请求)时发布xml数据

合同:

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) {...} 
} 

这是因为WCF期待您通过字符串使用Microsoft系列化命名空间进行序列化。如果你发送,

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

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

+0

Darrel, 谢谢。我尝试了你的建议。但是我仍然得到了相同的错误代码400.由于某些原因,如果我通过xml传递任何参数,服务无法识别该函数。如果我修改了该函数,以便不传递任何参数,则该函数已成功调用。还有其他建议吗? – 2010-06-17 16:10:20

+0

@Wayne尝试将字符串放入CDATA部分。 – 2010-06-19 18:29:20

在发送XML标签时,您需要在WebInvoke属性中将body style设置为Bare,如上面发送的那样。

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