c# Webmethod + Jquery post错误消息

本文关键字:错误 消息 post Jquery Webmethod | 更新日期: 2023-09-27 17:54:23

我正试图通过JQuery Post和Webmethod抛出一个处理过的异常,以便我可以将错误消息返回给警报函数。这只是一个测试脚本。

我已经设置好了,并且正在捕获错误,现在我需要将服务器错误返回给警报函数!

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string Test()
{
    try
    {
        string value = null;
        if (value.Length == 0) // <-- Causes exception
        {
            Console.WriteLine(value); // <-- Never reached
        }
    }
    catch (Exception E)
    {            
        StreamWriter sw = new StreamWriter(@"C:'inetpub'wwwroot'jQuery_AJAX_Database'error.txt", true);
        sw.WriteLine(E.Message);
        sw.Close();
        sw.Dispose();
        throw new Exception("error");
    }
    return "bla";

我的Post脚本:

 $("#btnTest").click(function () {
            $.ajax({
                type: 'POST',
                url: "my_test2.aspx/Test",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    alert('Success!')
                },
                error: function (xhr, status, error) {
                    var exception = JSON.parse(xhr.responseText);
                    alert(exception.Message);
                    // Here I need to return server error
                }
            });
        });

c# Webmethod + Jquery post错误消息

你需要一个http状态码。

把你的代码修改成

catch (Exception E)
    {            
        StreamWriter sw = new StreamWriter(@"C:'inetpub'wwwroot'jQuery_AJAX_Database'error.txt", true);
        sw.WriteLine(E.Message);
        sw.Close();
        sw.Dispose();
        return new HttpStatusCodeResult(500, E.Message);
    }

500代表internal server error。如果另一个更合适,你可以看看。

我想400 - Bad Request可能更适合你的情况。

谢谢@ted,你让我走上了正确的道路。解决如下!

throw new HttpException(E.Message);