Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery - using a POST request, which is not allowed Error

Tags:

jquery

I am trying to get jquery to communicate with a web service!!

  function Test(item) {
    $.ajax({
        type: 'POST',
        url: 'WebService.asmx/Test',
        data: '{ "Item" : "' + item + '" }',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (msg) {
            alert("oi");
        },
        error: function (msg) {
            alert('Get Details Failure: ' + msg);
        }
    });
};

using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
using System.Web.Script.Services;
using System.Web.Script.Serialization;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class WebService : System.Web.Services.WebService {

    public WebService () {}

    [System.Web.Services.WebMethod]
    [System.Web.Script.Services.ScriptMethod(UseHttpGet = true, ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)] 
    public string Test(string Item)
    {
        JavaScriptSerializer js = new JavaScriptSerializer();
        string strJSON = js.Serialize(Item);
        return strJSON;
    }

I get the following message:

{"Message":"An attempt was made to call the method \u0027Test\u0027 using a POST request, which is not allowed.","StackTrace":"   at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)\r\n   at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"}
like image 254
Beginner Avatar asked Jan 16 '12 17:01

Beginner


2 Answers

Your web service method is marked with a ScriptMethodAttribute that specifies UseHttpGet = true. Try removing this argument, or setting it to false. This is what is preventing the POST from working.

like image 134
David M Avatar answered Nov 07 '22 18:11

David M


Well, use a GET request, then (or change the webservice method to accept POST)

function Test(item) {
    $.ajax({
        type: 'GET',
        url: 'WebService.asmx/Test',
        data: {Item: item }, /* note change here, data is NOT a string! */
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (msg) {
            alert("oi");
        },
        error: function (msg) {
            alert('Get Details Failure: ' + msg);
        }
    });
};

Note that the data parameter is NOT a string (and, specifically, it is not JSON). You should pass a JavaScript object.

like image 2
Tomalak Avatar answered Nov 07 '22 19:11

Tomalak