【问题标题】:Getting Error: 500 Internal server error when using AJAX POST to C# Webmethod出现错误:使用 AJAX POST 到 C# Web 方法时出现 500 内部服务器错误
【发布时间】:2022-01-06 18:44:38
【问题描述】:
var image = document.getElementById("capture").toDataURL("image/png");
image = image.replace('data:image/png;base64,', '');

alert(image);

        $.ajax({
            type: 'POST',
            url: 'Info.aspx/testingPOST',
            data: '{ "imageData" : "' + image + '" }',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function(response, textStatus, jqXHR) {
                alert("File Saved");
            },
            error: function (jqXHR, exception) {
    var msg = 'error';
    if (jqXHR.status === 0) {
        msg = 'Not connect.\n Verify Network.';
    } else if (jqXHR.status == 404) {
        msg = 'Requested page not found. [404]';
    } else if (jqXHR.status == 500) {
        msg = 'Internal Server Error [500].';
    } else if (exception === 'parsererror') {
        msg = 'Requested JSON parse failed.';
    } else if (exception === 'timeout') {
        msg = 'Time out error.';
    } else if (exception === 'abort') {
        msg = 'Ajax request aborted.';
    } else {
        msg = 'Uncaught Error.\n' + jqXHR.responseText;
    }
    alert("error:" + msg);
    }
            })
        }

使用上面的方法将我的画布图像发布到 Web 方法,然后在下面的 c# 中进行简单的检查。我收到错误 500。 我查看了各种帖子,似乎找不到任何可以使其正常工作的调整,我已经关闭了 app_start 中的自动重定向和其他各种建议。但还是什么都没有。

[WebMethod]
    public static bool testingPOST(string value)
    {
        
        return true;
    }

【问题讨论】:

  • 首先,您需要配置服务器应用程序以报告错误的完整详细信息,以便更好地了解问题所在。
  • 尝试将data: '{ "imageData" : "' + image + '" }'改为data: { value : image }
  • 出于安全原因,默认情况下隐藏 500 错误详细信息。应该为生产服务器禁用它。具体操作方法因应用技术而异——因此您确实需要搜索特定设置(有时是版本)。
  • 我已经更改了 Cura 的建议,但仍然没有修复。
  • 我目前在 webconfig <httpErrors errorMode="Detailed" /> <asp scriptErrorSentToBrowser="true"/> 中使用,但在浏览器的详细信息中只收到 500 错误

标签: c# json ajax webmethod http-status-code-500


【解决方案1】:

WebMethod 告诉应用程序它是通过和 XML WebService 请求访问的。如果你想通过POST 访问它,你需要ScriptMethod 属性:

[ScriptMethod]
public static bool testingPOST(string value)
{
    return true;
}

查看此答案了解更多信息:

what is web method attribute in web service?

【讨论】:

  • 使用此更改仍然收到 500 错误。
  • [Webmethod] 是必需的,当我将其更改为 [Scriptmethod] 时,我会收到一个错误,提示缺少 Web 方法
【解决方案2】:

我在谷歌浏览器中使用开发者工具,点击错误,然后在预览中..它显示json字符串长度太长。

我使用以下内容编辑了 webconfig,现在可以使用了!

<system.web.extensions> 
<scripting> 
<webServices> 
<jsonSerialization maxJsonLength="500000000"/>
 </webServices> 
</scripting> 
</system.web.extensions>

【讨论】: