本文介绍了如何从webmethod返回异常到AJAX调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从 [WebMethod] 返回 List< strings> .但是,当发生异常时,如何向AJAX调用者返回 failure 消息?现在我出现构建错误.

I am returning List<strings> from [WebMethod]. But when exception occurs how to return failure message to AJAX caller?. Now I am getting build error.

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 Exception实例的JSON表示形式.您可以查看以下文章有关更多详细信息.

All exceptions thrown from a WebMethod get automatically serialized to the response as a JSON representation of a .NET Exception instance. You may checkout the following article for more details.

因此,您的服务器端代码可能会得到一些简化:

So your server side code could be a bit simplified:

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

And at the end of the day, after saying all this stuff, you should be aware that WebMethods are a completely outdated and obsolete technology and unless you are maintaining some existing code, you have absolutely no excuse on using them in new projects.

这篇关于如何从webmethod返回异常到AJAX调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 12:28