POST JSON data in .asmx webservice

I am trying to publish some simple parameters for the .asmx web service.
I get the following error: The request format is invalid: application / json; encoding = UTF-8.
What I really need is to pass in a complex object, but I can't get past the POST request with the json content type.

Here is my definition of WebService

[WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public int JsonTest2(int myparm1, int myparm2) { return 101; } 

And this is my javascript code

 function JsonTest2() { $.ajax({ type: 'POST', url: "http://localhost/WebServices/MyTest.asmx/JsonTest2", data: "{myparm1:105,myparm2:23}", contentType: 'application/json; charset=UTF-8', dataType: 'json', async: false, success: function (msg) { alert(msg); }, error: function (msg) { alert('failure'); alert(msg); } }); } 
+7
source share
3 answers

Verify that the ASMX class of service is decorated with the [ScriptService] attribute.

+5
source

You should use a value formatted as valid JSON data as data:

 {"myparm1":105,"myparm2":23} 

instead

 {myparm1:105,myparm2:23} 

You can check on the website http://www.jsonlint.com/ whose data is JSON data. Therefore you must change your code to

 $.ajax({ type: 'POST', url: "http://localhost/WebServices/MyTest.asmx/JsonTest2", data: '{"myparm1":105,"myparm2":23}', contentType: 'application/json; charset=UTF-8', dataType: 'json', async: false, success: function (msg) { alert(msg.d); }, error: function (msg) { alert('failure'); alert(msg); } }); 

For more complex input parameters, I recommend using the JSON.stringify function from json2.js (see this answer ):

 var myValue1 = 105, myValue2 = 23; $.ajax({ type: 'POST', data: JSON.stringify({myparm1:myValue1, myparm2:myValue2}), ... }); 

In the latest version of $.ajax using myValue1 and myValue2 can be complex structures (objects with properties) or arrays that even have other complex structures or arrays as properties.

+1
source

Make sure the URL contains the port number when using localhost.

  url: "http://localhost:1297/WebServices/MyTest.asmx/JsonTest2", 
0
source

All Articles