【问题标题】:how to return exception to AJAX call from webmethod?如何从 webmethod 向 AJAX 调用返回异常?
【发布时间】:2014-09-23 19:08:36
【问题描述】:

我从[WebMethod] 返回List<strings>。但是当发生异常时如何将failure 消息返回给 AJAX 调用者?现在我收到构建错误。

JS:

$.ajax({
    type: 'POST',
    contentType: "application/json; charset=utf-8",
    url: 'new.aspx/GetPrevious',
    data: "{'name':'" + username + "'}",
    async: false,
    success: function (data) {
        Previous = data.d;
        alert(salts);
    },
    error: function () {
        alert("Error");
    }
});

C#:

[WebMethod]
public static List<string> GetPreviousSaltsAndHashes(string name)
{
    try
    {
        List<string> prevSalts = new List<string>();
        if (reader.HasRows)
        {
            while (reader.Read())
            {                      
                prevSalts.Add(reader.GetString(0));
            }
        }
        conn.Close();
        return prevSalts;
    }
    catch (Exception ex)
    {
        return "failure"; //error showing here
    }
}

【问题讨论】:

    标签: c# jquery ajax


    【解决方案1】:

    WebMethod 引发的所有异常都会自动序列化为响应,作为 .NET 异常实例的 JSON 表示。您可以查看following article 了解更多详情。

    所以你的服务器端代码可以稍微简化一下:

    [WebMethod]
    public static List<string> GetPreviousSaltsAndHashes(string name)
    {
        List<string> prevSalts = new List<string>();
    
        // Note: This totally sticks. It's unclear what this reader instance is but if it is a 
        // SqlReader, as it name suggests, it should probably be wrapped in a using statement
        if (reader.HasRows)
        {
            while (reader.Read())
            {                      
                prevSalts.Add(reader.GetString(0));
            }
        }
    
        // Note: This totally sticks. It's unclear what this conn instance is but if it is a 
        // SqlConnection, as it name suggests, it should probably be wrapped in a using statement
        conn.Close();
    
            return prevSalts;
        }
    }
    

    在客户端:

    error: function (xhr, status, error) {
        var exception = JSON.parse(xhr.responseText);
        // exception will contain all the details you might need. For example you could
        // show the exception Message property
        alert(exception.Message);
    }
    

    归根结底,在说了这么多事情之后,您应该意识到 WebMethods 是一种完全过时和过时的技术,除非您要维护一些现有代码,否则您绝对没有理由在新项目中使用它们.

    【讨论】:

      【解决方案2】:

      您可以返回带有正文(您的实际数据)、状态代码和错误字段的通用结构,以描述异常(如果有)。然后在 JS 方面,您只需要根据状态代码使用正文或错误字段。这就是我在上一个肥皂网络服务中使用的。

      【讨论】:

        【解决方案3】:

        确保在两种情况下都返回相同的类型。将你的失败变成一个列表:

        List<string> prevSalts = new List<string>();
        try
        {
            ...
        }
        catch (Exception ex)
        {
            prevSalts.Clear();
            prevSalts.Add("failure");     
        }
        return Json(new 
        {
            salts = prevSalts
        }, JsonRequestBehavior.AllowGet);
        

        编辑:要在前端获取您的字符串,请在适当的方法中检查它

        success: function (data) {
            Previous = data.salts
            alert(salts);
        },
        error: function (data) {
           $.each(data.salts, function(index,item) {
                alert(item);
           }); 
        }
        

        【讨论】:

        • 但是我怎样才能发现错误:AJAX 中的 function ()?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-26
        • 2019-12-04
        • 2012-03-29
        相关资源
        最近更新 更多