views:

1887

answers:

3

I'm tryint to post to a ADO.NET Data Service but the parameters seems to get lost along the way.

I got something like:

[WebInvoke(Method="POST")]
public int MyMethod(int foo, string bar) {...}

and I make an ajax-call using prototype.js as:

var args = {foo: 4, bar: "'test'"};
new Ajax.Requst(baseurl + 'MyMethod',
  method: 'POST',
  parameters: args,
  onSuccess: jadda,
  onFailure: jidda
}

If I replace "method: 'POST'" with "method: 'GET'" and "WebInvoke(Method="POST")" with "WebGet" everything works but now (using post) all I get is:

Bad Request - Error in query syntax.

from the service.

The only fix (that I don't want to use) is to send all parameters in the URL even when I perform a post. Any ideas are welcome.

A: 

If you want to use POST, you need to specify the parameters to be wrapped in the request in WebInvoke attribute unless the parameters contains on object (e.g. message contract). This makes sense since there is no way to serialize the parameters without wrapped in either json or xml.

Unwrapped which is not XML indeed as missing root element

<foo>1</foo>
<bar>abc</bar>

Wrapped, valid XML

<Request>
   <foo>1</foo>
   <bar>abc</bar>
</Request>

This sample also applies to JSON

codemeit
A: 

Are you saying that I should wrap the parameters i the javascript like

var args = {Request: {foo: 3, bar: "'test'"}}

or am I missing something?

I've tried to add:

ResponseFormat=WebMessageFormat.Json, RequestFormat=WebMessageFormat.Json, BodyStyle=WebMessageBodyStyle.Wrapped

to the WebInvoke-attribute but with no result. I've tried to set "Content-Type" (in js POST ajax-call) to "application/x-www-form-urlencoding" and "application/json; charset=utf-8" but with no result.

finnsson
+1  A: 

WCF and ASMX webservices tend to be a bit choosey about the request body, when you specify args the request is usually encoded as a form post i.e. foo=4&bar=test instead you need to specify the javascript literal:-

   new Ajax.Request(baseurl + 'MyMethod', {
        method: 'POST',
        postBody: '{"foo":4, "bar":"test"}',
        encoding: "UTF-8",
        contentType: "application/json;",
        onSuccess: function(result) {
            alert(result.responseJSON.d); 
        },
        onFailure: function() {
            alert("Error");
        }
    });
sighohwell