POST JSON data to .asmx webservice

2019-04-07 11:52发布

问题:

I'm trying to post some simple parameters to a .asmx webservice.
I get the following error: Request format is invalid: application/json; charset=utf-8.
What I really need to get to is to be able to pass a complex object, but I can't get past making a POST request with json content type.

Here is my WebService Definition

[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);
        }
    });
}

回答1:

Make sure your ASMX service class is decorated with the [ScriptService] attribute.



回答2:

You should use as data the value which formatted as correct JSON data:

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

instead of

{myparm1:105,myparm2:23}

You can validate on the site http://www.jsonlint.com/ which data are JSON data. So you should 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);
    }
});

In case of more complex input parameters I recommend you to use JSON.stringify functionfrom the json2.js (see this answer for example):

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

In the last version of $.ajax usage the myValue1 and myValue2 can be complex structures (objects with properties) or arrays having even another complex structures or arrays as the properties.



回答3:

Make sure the URL contains port number when using localhost.

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