WCF Restful services getting error 400 (bad request) when post xml data
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.
Contract:
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);
}
Server side code:
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.XML开发者_运维知识库HttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {...}
}
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.
You require to set body style to Bare in the WebInvoke attribute as shown in below snippet while sending XML tags like you have sent in above.
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = INFOMATO.RestTemplate.hello_post2,RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Bare)]
Stream hello_post2(string helloString);
精彩评论