How to return an error from a web method?

How to return error in aspx page method decorated with WebMethod ?

Code example

 $.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 to return an error from a web method? That way you can use the jquery error part to show the error details.

+4
source share
3 answers

I don't know if there is a more WebMethod -special way to do this, but in ASP.NET you would just set the status code for the Response Object . Something like that:

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

Using standard error codes is an appropriate way to notify the consumer of an HTTP client about an error. Before ending the response, you can also Response.Write() send any messages. The formats for them are much less standardized, so you can create your own. But while the status code accurately reflects the answer, your JavaScript or any other client that consumes this service will understand the error.

+6
source

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

 function onAjaxFailed(error){ alert(error); } 
+3
source

The error is indicated by the http status code (4xx - user request error, 5xx - internal server error) on the results page. I don't know asp.net, but I think you need to throw an exception or something like that.

+1
source

Source: https://habr.com/ru/post/1369304/


All Articles