从javascript调用webmethod时,ASP.NET 500内部服务器出错
我试图使用AJAX调用webmethod
fucntionality但无法获得适当的结果。 我搜索了我的问题并找到了许多解决方案,但那些对我没用。 请指导我做错了什么。 帮助将不胜感激。
干杯
代码片段
function checkUserNameExists() { //initialization var pagePath = window.location.pathname + "/getUsername"; var value = document.getElementById('control_userName').value; var dataString = "{ 'value':'" + value + "' }"; $.ajax({ type: "GET", url: pagePath, data: dataString, contentType: "application/json; charset=utf-8", dataType: "json", error: function (XMLHttpRequest, textStatus, errorThrown) { }, success: function (result) { var flag = true; if (result != null) { flag = result.d; if (flag == "True") { alert('okay fine you are good'); } else { alert('try again'); } } } }); }
代码文件后面的方法
[WebMethod] [ScriptMethod(UseHttpGet = true)] public string getUsername(string value) { return "True"; }
例外
ExceptionType: "System.InvalidOperationException" Message: "An attempt was made to call the method 'getUsername' using a POST request, which is not allowed."
首先,webmethod是在页面类中,而不是在Webservice类中,那么它应该是静态的。
其次,传输的数据实际上不是字符串,而是一个对象,因此将其更改为:
var dataString = { 'value': value };
第三件事,“类型”是旧版本的jquery,您应该将ajax调用更改为:
method: "GET", url: pagePath, data: dataString, contentType: "application/json; charset=utf-8", dataType: "json",...
或者通过删除,更改服务器端的function以获得发布呼叫
UseHttpGet = true
您可能需要在方法声明中添加静态,如下所示
[WebMethod] [ScriptMethod(UseHttpGet = true)] public static string getUsername(string value) { return "True"; }
如果不是这种情况,您可以使用F12浏览器 – >网络,然后单击错误消息进行简要查看。
关于报告的问题,get请求的问题,尽量让它发布
答案在这里: 链接
问题在于我使用的[ScriptMethod(UseHttpGet = true)]
注释会导致错误。 只需将值从true更改为false。
这不是特定于这个问题,但你可以检查一些事情,以更好地了解导致问题的原因。
- 在“ 请求标头”的“常规”部分中检查请求的状态代码和类型。
- 如果有任何json错误,请检查响应标头 。
- 检查响应以获取消息,堆栈跟踪和exception类型。
- 检查Headers中的Request Payload部分是否已传递参数。
查看此post了解更多详情。