向ajax请求返回错误的最佳方式是怎样的?

问题描述 投票:0回答:2

当从 ajax 调用一个 WebMethod 时,如果我返回一个简单的字符串,ajax 代码会毫无错误地转到 success 方法,如下所示:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string Hello()
{
    return "Hello World";
}

这是正确的,但是,如何使 WebMethod 返回错误并在 ajax 错误方法而不是成功方法中捕获错误?

谢谢

c# json ajax webmethod
2个回答
5
投票

更改您的回复状态代码:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string Hello()
{
    Response.StatusCode = 400 ; // Will be captured on ajax error method 
    return "Hello World";
}

0
投票

我必须使用下面的方法,因为静态 WebMethod 无法提供响应

System.Web.HttpContext.Current.Response.StatusCode = 500;
© www.soinside.com 2019 - 2024. All rights reserved.