我正在尝试自我托管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) {...}
}
答案 0 :(得分:1)
这是因为WCF期望您传递的字符串使用Microsoft序列化命名空间进行序列化。如果你发送,
<string xmlns='http://schemas.microsoft.com/2003/10/Serialization/'>hello via Post</string>
那么它可能会正确地反序列化。
答案 1 :(得分:0)
您需要在WebInvoke属性中将正文样式设置为Bare,如下面的代码段所示,同时发送您在上面发送的XML标记。
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = INFOMATO.RestTemplate.hello_post2,RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Bare)]
Stream hello_post2(string helloString);