如何从 webmethod 返回错误?
如何在用 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 错误部分来显示错误详细信息。
How does one return an error in an aspx page method decorated with WebMethod
?
Sample Code
$.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()
{
}
How does one return error from a webmethod? So one can be able to use the jquery error portion to show the error detail.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我不知道是否有更特定于
WebMethod
的方法,但在 ASP.NET 中,您通常只需为 响应对象。像这样的事情:使用标准错误代码是向消费 HTTP 客户端通知错误的适当方法。在结束响应之前,您还可以
Response.Write()
您想要发送的任何消息。这些格式的标准化程度要低得多,因此您可以创建自己的格式。但只要状态代码准确地反映了响应,那么您的 JavaScript 或使用该服务的任何其他客户端就会理解该错误。I don't know if there's a more
WebMethod
-specific way of doing it, but in ASP.NET you'd generally just set the status code for your Response object. Something like this:Using standard error codes is the appropriate way to notify a consuming HTTP client of an error. Before ending the response you can also
Response.Write()
any messages you want to send. The formats for those are much less standardized, so you can create your own. But as long as the status code accurately reflects the response then your JavaScript or any other client consuming that service will understand the error.只需在 PageMethod 中抛出异常并在 AjaxFailed 中捕获它即可。像这样的东西:
Just throw the exception in your PageMethod and catch it in AjaxFailed. Something like that:
结果页面的 http 状态代码(4xx - 用户请求故障,5xx - 内部服务器故障)指示错误。我不知道asp.net,但我想你必须抛出异常或类似的东西。
An error is indicated by the http status code (4xx - user request fault, 5xx - internal server fault) of the result page. I don't know asp.net, but I guess you have to throw an exception or something like that.
JQuery xhr 将在responseText/responseJSON 属性中返回错误和堆栈跟踪。
例如:
C#:
JavaScript:
the JQuery xhr will return the error and stack trace in the responseText/responseJSON properties.
For Example:
C#:
Javascript:
我尝试了所有这些解决方案以及其他 StackOverflow 答案:
对我来说没有任何作用。
所以我决定自己手动捕获
[WebMethod]
错误。看我的例子:
I tried all those solutions among with other StackOverflow answers:
Nothing worked for me.
So I decided simply to catch
[WebMethod]
errors by myself manually.See my example: