由于不允许GET请求,POST请求失败

时间:2014-06-19 13:40:19

标签: c# jquery ajax

我的代码中有一个WebMethod,我正在通过AJAX调用。该方法在使用GET请求时有效,但我更喜欢使用POST,我也想知道为什么这不起作用和/或我做错了什么。

的JavaScript

 $(document).ready(function () {
        $.ajax({
            url: "Default.aspx/HelloWorld",
            method: "POST",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                $("#test1").html(data.d);
            },
            error: function (err) {
                $("#errOutput").text("ERROR: " + err.responseText);
            }
        });
    });

C#

    [WebMethod]
    [ScriptMethod(UseHttpGet=false)]
    public static string HelloWorld() 
    {
        return "Hello World!";
    }

错误

Message:
"An attempt was made to call the method \u0027HelloWorld\u0027 using a 
GET 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"

1 个答案:

答案 0 :(得分:2)

看一些jQuery documentation我认为您使用了错误的属性。我怀疑这个:

method: "POST"

应该是

type: "POST"

method对我来说也是一个更明智的名字,但我们去了......

(免责声明:我自己从未使用过jQuery ......这个答案完全基于文档。)

相关问题