如何在用
WebMethod
装饰的 aspx 页面方法中返回错误?
示例代码
$.ajax({
type: "POST",
url: "./Default.aspx/GetData",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
[WebMethod]
public static string GetData()
{
}
如何从 webmethod 返回错误?因此可以使用 jquery 错误部分来显示错误详细信息。
我不知道是否有更针对
WebMethod
的具体方法,但在 ASP.NET 中,您通常只需为 Response 对象 设置状态代码。像这样的东西:
Response.Clear();
Response.StatusCode = 500; // or whatever code is appropriate
Response.End;
使用标准错误代码是向使用 HTTP 客户端通知错误的适当方法。在结束回复之前,您还可以
Response.Write()
您想要发送的任何消息。这些格式的标准化程度要低得多,因此您可以创建自己的格式。但只要状态代码准确地反映了响应,那么您的 JavaScript 或使用该服务的任何其他客户端就会理解该错误。
只需在 PageMethod 中抛出异常并在 AjaxFailed 中捕获它即可。类似这样的东西:
function onAjaxFailed(error){
alert(error);
}
结果页面的 http 状态代码(4xx - 用户请求故障,5xx - 内部服务器故障)指示错误。我不知道 asp.net,但我想你必须抛出异常或类似的东西。
JQuery xhr 将在responseText/responseJSON 属性中返回错误和堆栈跟踪。
例如: C#:
throw new Exception("Error message");
Javascript:
$.ajax({
type: "POST",
url: "./Default.aspx/GetData",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
function AjaxFailed (jqXHR, textStatus, errorThrown) {
alert(jqXHR.responseJSON.Message);
}
我尝试了所有这些解决方案以及其他 StackOverflow 答案。对我来说没有任何作用。
所以我决定自己手动捕获
[WebMethod]
错误。
看我的例子:
[WebMethod]
public static WebMethodResponse GetData(string param1, string param2)
{
try
{
// You business logic to get data.
var jsonData = myBusinessService.GetData(param1, param2);
return new WebMethodResponse { Success = jsonData };
}
catch (Exception exc)
{
if (exc is ValidationException) // Custom validation exception (like 400)
{
return new WebMethodResponse { Error = "Please verify your form: " + exc.Message };
}
else // Internal server error (like 500)
{
var errRef = MyLogger.LogError(exc, HttpContext.Current);
return new WebMethodResponse { Error = "Some error occurred please contact with administrator. Error ref: " + errRef };
}
}
}
public class WebMethodResponse
{
public string Success { get; set; }
public string Error { get; set; }
}