从jQuery调用.asmx web服务:不允许GET?

时间:2013-09-09 17:35:18

标签: jquery asp.net web-services asmx .net-4.5

我有一个简单的页面。在加载时,它调用Web服务,然后我收到以下错误:

an attempt was made to call the method using a GET request, which is not allowed

我的JS代码:

    function getTutors() {
        var url = '<%= ResolveUrl("~/services/tutorservice.asmx/gettutors") %>';
        $.ajax({
            type: "GET",
            data: "{'data':'" + 'test-data' + "'}",
            url: url,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (d) {
                alert('succes');
                return d;
            },
            error: function () {
                alert('fejl');
            }
        });
    }

    $(document).ready(function () {
        var tutors = getTutors();
        var locations = [];
    }

我的网络服务:

    [ScriptService]
public class tutorservice : System.Web.Services.WebService {

    public tutorservice () {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    [WebMethod]
    public List<Tutor> gettutors(string data)
    {
        var tutorManager = new TutorManager();
        return tutorManager.GetTutorApplicants();
    }

}

我试图删除contentTypes,即使没有数据变量,它仍然会给出相同的错误。

我最好的猜测是应删除一些contentType / dataType,但我也试过了。

关于我为何会收到此错误的任何想法?

1 个答案:

答案 0 :(得分:4)

我可以想到两个选择:

1)在AJAX通话中使用POST而不是GET:

type: "POST",

或2)如果必须使用GET,请配置Web服务方法以允许GETS:

[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public List<Tutor> gettutors(string data)
{
    var tutorManager = new TutorManager();
    return tutorManager.GetTutorApplicants();
}

并通过web.config允许GETS:

<webServices>
  <protocols>
    <add name="HttpGet"/>
    <add name="HttpPost"/>
  </protocols>
</webServices>
相关问题