使用jQueryAjax调用WebMethod的"GET"方法

18

我有一个使用"POST"可以正常工作的Ajax请求,但是当我使用"GET"时,它会给我以下错误信息:

{"Message":"An attempt was made to call the method \u0027GetSomething\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"}

这是我的代码,在客户端:

function test() {
        $.ajax({
            url: "Default4.aspx/GetSomething",
            type: "GET",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function (res) { debugger; alert(res.d); },
            error: function (res) { debugger; alert("error"); }
        });
    }

在服务器端,

[WebMethod]
public static string GetSomething()
{
    return "got something";
}

当我使用"GET"时,为什么会出错?

3个回答

69

如果您想使用GET方式调用它,您需要添加:

[WebMethod]
[ScriptMethod(UseHttpGet=true)]
....

1
我也曾经遇到过同样的问题。谢谢。 - jkl

2

另一种方法:您可以将其添加到配置文件中

<system.web>
    ...
    <webServices>
        <protocols>
              <add name="HttpGet"/>
        </protocols>
    </webServices>
    ...
</system.web>

两种选项都可以:使用 ScriptMethod(UseHttpGet=true) 进行装饰,或者在 webconfig 中添加大小写敏感的 webServices 条目。 - fcm

1

在Web.config文件的</configuration>标签之前添加以下代码。

<location path="webservice.asmx">
  <system.web>
    <webServices>
      <protocols>
        <add name="HttpGet"/>
        <add name="HttpPost"/>
      </protocols>
    </webServices>
  </system.web>
</location>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接