在ajax错误上显示来自服务器的异常消息

Inb*_*bal 9 c# ajax jquery

我使用以下代码来显示客户端上的服务器的异常消息:

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static void test(String text)
    {
               try
               {
                    throw new Exception("Hello");
               }

               catch (Exception ex)
               {
                HttpContext.Current.Response.Write(ex.Message);
                throw new Exception(ex.Message, ex.InnerException);
               }

    }
Run Code Online (Sandbox Code Playgroud)

客户端:

    $.ajax({
        url: 'DownloadFile.aspx/test',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        // Pass the value as JSON string                 
        // You might need to include json2.js for the JSON.stringify
        //method: 'http://www.json.org/json2.js',
        async: false,
        dataType: "json",
        data: '{ "text": "' + text'"}',
        success: function(Result) {

        },

        error: function(xhr, textStatus, errorThrown) {
            var err = eval("(" + xhr.responseText + ")");
            alert(err.Message);
        }
    });
Run Code Online (Sandbox Code Playgroud)

当我使用localhost时,我在警告弹出窗口中显示"Hello".当我在远程服务器上使用相同的代码时,我得到一般系统错误.

如何向用户显示异常消息文本?

小智 3

您需要<customErrors mode="Off" />在 web.config 中进行设置。

你可以在这里阅读更多

一般来说,您的模式似乎是“RemoteOnly”,它仅向本地主机显示详细的异常消息。