【问题标题】:Calling .asmx webservice from jQuery: GET is not allowed?从 jQuery 调用 .asmx Web 服务:不允许 GET?
【发布时间】:2013-09-09 17:35:18
【问题描述】:

我有一个简单的页面。在加载时,它会调用 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,即使没有 data 变量,它仍然会给出同样的错误。

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

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

【问题讨论】:

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


    【解决方案1】:

    我能想到两个选择:

    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>
    

    【讨论】:

    • 解决了我选择 POST 的问题...谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-31
    • 2013-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-12
    • 1970-01-01
    相关资源
    最近更新 更多