1

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.XMLHttpRequest) {
      xhr = new XMLHttpRequest();
      } else if (window.ActiveXObject) {...}
}
Wayne Lo
  • 3,689
  • 2
  • 28
  • 28

2 Answers2

1

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.

Darrel Miller
  • 139,164
  • 32
  • 194
  • 243
  • Darrel, Thanks. I tried your suggestion. But I still got the same error code 400. For some reasons, if I passed any parameters via xml, the services failed to recognize the function. If I modified the function so that no parameters were passed, the function was successfully invoked. Any other suggestions? – Wayne Lo Jun 17 '10 at 16:10
  • @Wayne Try putting the string inside a CDATA section. – Darrel Miller Jun 19 '10 at 18:29
0

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);
Jenish Rabadiya
  • 6,708
  • 6
  • 33
  • 62