How to return error from webmethod?

走远了吗. 提交于 2019-12-23 12:16:10

问题


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.


回答1:


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:

Response.Clear();
Response.StatusCode = 500; // or whatever code is appropriate
Response.End;

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.




回答2:


Just throw the exception in your PageMethod and catch it in AjaxFailed. Something like that:

function onAjaxFailed(error){
     alert(error);
}



回答3:


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.



来源:https://stackoverflow.com/questions/7216195/how-to-return-error-from-webmethod

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!