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

时间:2014-09-23 19:08:36

标签: c# jquery ajax

我将从List<strings>返回[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
    }
}

3 个答案:

答案 0 :(得分:2)

WebMethod抛出的所有异常都会自动序列化为响应,作为.NET Exception实例的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是一种完全过时且过时的技术,除非您维护一些现有代码,否则您绝对没有理由在新项目中使用它们

答案 1 :(得分:0)

确保在两种情况下都返回相同的类型。将您的失败更改为列表:

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);
   }); 
}

答案 2 :(得分:0)

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