WCF Restful 服务在发布 xml 数据时出现错误 400(错误请求) [英] WCF Restful services getting error 400 (bad request) when post xml data
本文介绍了WCF Restful 服务在发布 xml 数据时出现错误 400(错误请求)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试自行托管 WCF 服务并通过 javascript 调用这些服务.当我通过 Json 传递请求数据而不是 xml(400 错误请求)时,它起作用.请帮忙.
I am trying to self host a WCF services and calling the services via javascript. It works when I pass the request data via Json but not xml (400 bad request). Please help.
合同:
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:
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 序列化命名空间进行序列化.如果您发送,
That's because WCF is expecting the string you pass to be serialized using the Microsoft serialization namespace. If you send,
<string xmlns='http://schemas.microsoft.com/2003/10/Serialization/'>hello via Post</string>
那么它可能会正确反序列化.
then it will probably deserialize properly.
这篇关于WCF Restful 服务在发布 xml 数据时出现错误 400(错误请求)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文