views:

404

answers:

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

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/'&gt;hello via Post</string>

then it will probably deserialize properly.

Darrel Miller
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
@Wayne Try putting the string inside a CDATA section.
Darrel Miller