当我尝试使用 jquery ajax 从 '.asmx' 网络服务获取数据时,如何调试“500 内部错误”

How do I debug the "500 internal error" when I am trying to get data form '.asmx' webservice using jquery ajax

我正在尝试使用 jquery 向我的 asp.net 服务器发送 ajax 请求并获取一些数据 back.But 我无法做到这一点 seems.No 不管我做什么我都会得到 Failed to load resource: the server responded with a status of 500 (Internal Server Error) 错误 massege.I 知道这是一个重复的问题,但我几乎阅读了我在 Whosebug 和其他网站上可以阅读的所有内容,并且 none解决方案有帮助 me.I 我正在尝试调试这个东西并弄清楚我能做什么,但我不知道我必须怎么做

这是我的代码:

这是 ajax 调用:

$(document).ready(function () {
    $('.list-item button').on('click', function () {
        $.ajax({
            type: "POST", //HTTP method
            url: "/WebServices/RequestHandler.asmx/HelloWorld", 
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: "{}",
            success: function (msg) {               
            console.log(msg);
            },
            error: function (xhr, textStatus, thrownerror) {
            alert("something went wrong");
            console.log(xhr.status);
            console.log(xhr.responseText);
            console.log(thrownerror);
            }
        });
    });
});

这是我的网络服务:

[WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class RequestHandler : System.Web.Services.WebService
    {
        private string connectionString = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;

        [WebMethod]
        public static string HelloWorld()
        {
            return "hello";
        }
    }

如您所见,这是一个非常简单的方法,我只是想弄清楚发生了什么以及为什么它不起作用

是的,我确实省略了这两部分:

contentType: "application/json; charset=utf-8",
dataType: "json",

到处都建议了数千次,但根本没有帮助。

还有在浏览器控制台中触发错误消息时的代码:

<!DOCTYPE html>
<html>
    <head>
        <title>Request format is unrecognized for URL unexpectedly ending in '/HelloWorld'.</title>
        <meta name="viewport" content="width=device-width" />
        <style>
         body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;} 
         p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
         b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
         H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
         H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
         pre {font-family:"Consolas","Lucida Console",Monospace;font-size:11pt;margin:0;padding:0.5em;line-height:14pt}
         .marker {font-weight: bold; color: black;text-decoration: none;}
         .version {color: gray;}
         .error {margin-bottom: 10px;}
         .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }
         @media screen and (max-width: 639px) {
          pre { width: 440px; overflow: auto; white-space: pre-wrap; word-wrap: break-word; }
         }
         @media screen and (max-width: 479px) {
          pre { width: 280px; }
         }
        </style>
    </head>

    <body bgcolor="white">

            <span><H1>Server Error in '/' Application.<hr width=100% size=1 color=silver></H1>

            <h2> <i>Request format is unrecognized for URL unexpectedly ending in '/HelloWorld'.</i> </h2></span>

            <font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">

            <b> Description: </b>An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

            <br><br>

            <b> Exception Details: </b>System.InvalidOperationException: Request format is unrecognized for URL unexpectedly ending in '/HelloWorld'.<br><br>

            <b>Source Error:</b> <br><br>

            <table width=100% bgcolor="#ffffcc">
               <tr>
                  <td>
                      <code>

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.</code>

                  </td>
               </tr>
            </table>

            <br>

            <b>Stack Trace:</b> <br><br>

            <table width=100% bgcolor="#ffffcc">
               <tr>
                  <td>
                      <code><pre>

[InvalidOperationException: Request format is unrecognized for URL unexpectedly ending in &#39;/HelloWorld&#39;.]
   System.Web.Services.Protocols.WebServiceHandlerFactory.CoreGetHandler(Type type, HttpContext context, HttpRequest request, HttpResponse response) +489329
   System.Web.Services.Protocols.WebServiceHandlerFactory.GetHandler(HttpContext context, String verb, String url, String filePath) +212
   System.Web.Script.Services.ScriptHandlerFactory.GetHandler(HttpContext context, String requestType, String url, String pathTranslated) +47
   System.Web.MaterializeHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +346
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; completedSynchronously) +155
</pre></code>

                  </td>
               </tr>
            </table>

            <br>

            <hr width=100% size=1 color=silver>

            <b>Version Information:</b>&nbsp;Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18408

            </font>

    </body>
</html>
<!-- 
[InvalidOperationException]: Request format is unrecognized for URL unexpectedly ending in &#39;/HelloWorld&#39;.
   at System.Web.Services.Protocols.WebServiceHandlerFactory.CoreGetHandler(Type type, HttpContext context, HttpRequest request, HttpResponse response)
   at System.Web.Services.Protocols.WebServiceHandlerFactory.GetHandler(HttpContext context, String verb, String url, String filePath)
   at System.Web.Script.Services.ScriptHandlerFactory.GetHandler(HttpContext context, String requestType, String url, String pathTranslated)
   at System.Web.HttpApplication.MaterializeHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
-->

从上面的错误消息中我可以理解,url 有问题,它不是 "FORMATTED CORRECTLY" 之类的,我真的不知道我能做些什么来解决这个错误.

如有任何想法,我们将不胜感激

提前致谢

更新 我还在某处读到默认情况下禁用 GET 和 POST 请求,因此我还将这些协议添加到我的 Web.config 文件中:

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

但我还是遇到了同样的问题

如果您想使用 GET 调用您的 WebMethod,您需要添加一个 ScriptMethod 属性以允许它:

[WebMethod]
[ScriptMethod(UseHttpGet=true)]
public static string HelloWorld()
{
    return "hello";
}

来自documentation

If a method is not marked with ScriptMethodAttribute, the method will be called by using the HTTP POST command and the response will be serialized as JSON

或者,使用 POST 访问 WebMethod。

好的,所以我终于弄明白了,事实证明,这是我的 .net 的问题 framework.I 使用本教程重新安装了我机器上安装的 .net 框架,重新启动了我的电脑,省略了我的 webmethodstatic 声明,现在一切正常