调用使用jQueryAjax一个WebMethod“GET”(Calling a WebMethod

2019-06-24 19:09发布

我有一个Ajax请求效果很好使用“POST”,但使用时,“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”我得到的错误?

Answer 1:

如果你想调用用得到它,你需要添加:

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


Answer 2:

另一种方法:你可以在配置文件中添加它

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


Answer 3:

你应该在网页config文件的标记之前添加以下代码。

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


文章来源: Calling a WebMethod using jQueryAjax “GET”