如何从 webmethod 向 AJAX 调用返回异常?

2024-05-26

我回来了List<strings> from [WebMethod]。但是当异常发生时如何返回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
    }
}

所有异常抛出自WebMethod自动序列化为响应,作为 .NET 异常实例的 JSON 表示形式。您可以查看以下文章 http://encosia.com/use-jquery-to-catch-and-display-aspnet-ajax-service-errors/更多细节。

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

[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 是一种完全过时且过时的技术,除非您维护一些现有代码,否则您绝对没有借口在新项目中使用它们。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何从 webmethod 向 AJAX 调用返回异常? 的相关文章

随机推荐