如何从ASP.NET WebForm的WebMethod向jQuery AJAX请求返回成功和错误消息
ASP.NET WebForm WebMethod成功返回实现方案
首先明确:[WebMethod]特性是ASP.NET WebForm的专属能力,不支持Web API体系下的IHttpActionResult类型返回,你当前的方法返回值定义需要调整。
实现步骤
1. 定义通用返回结构(可选)
如果需要同时返回状态码、提示信息、业务数据三个维度的内容,可自定义统一返回类:
public class AjaxResponse { /// <summary> /// 业务状态码,200代表成功 /// </summary> public int Code { get; set; } /// <summary> /// 提示信息 /// </summary> public string Msg { get; set; } /// <summary> /// 业务数据 /// </summary> public object Data { get; set; } }
如果只需要返回业务数据,直接把方法返回值设置为对应的数据类型即可,比如你场景中需要返回字符串,就将返回值设为Task<string>。
2. 修正WebMethod代码
调整返回类型后,成功场景直接返回封装好的结果即可,异常场景的HttpResponseException抛出逻辑可以保留,会自动被前端AJAX的error回调捕获。
修正后的代码示例:
[WebMethod()] public async Task<AjaxResponse> ProcessData(CustomerData customerData) { try { HttpClient client = new HttpClient(); HttpResponseMessage resp = await client.PostAsync("<你的请求地址>", <你的请求参数>); if (resp.IsSuccessStatusCode) { string result = await resp.Content.ReadAsStringAsync(); // 直接返回成功结果 return new AjaxResponse { Code = 200, Msg = "处理成功", Data = result }; } else { string reasonAndStatusCode = resp.StatusCode + "; " + resp.ReasonPhrase; string errorMessage = "方法名: ProcessData. 客户数据处理失败. 状态码与原因: " + reasonAndStatusCode; HttpResponseMessage error = GenerateError(resp.StatusCode, errorMessage); throw new HttpResponseException(error); } } catch (Exception ex) { string errorMessage = "方法名: ProcessData. 服务内部错误: " + ex.Message; HttpResponseMessage error = GenerateError(HttpStatusCode.InternalServerError, errorMessage); throw new HttpResponseException(error); } }
3. 前端AJAX对应处理
WebMethod的返回结果默认会被包裹在d字段中,前端取值时需要注意:
$.ajax({ type: "POST", url: "你的页面名称.aspx/ProcessData", contentType: "application/json; charset=utf-8", data: JSON.stringify({ customerData: 你的业务参数 }), dataType: "json", success: function (res) { // res.d就是后台返回的AjaxResponse对象 if(res.d.Code === 200) { console.log("处理成功,业务数据:", res.d.Data); } }, error: function (xhr) { // xhr.status为后台设置的HTTP状态码,xhr.responseText为错误信息 console.log("处理失败,状态码:" + xhr.status + ",错误信息:" + xhr.responseText); } });
内容的提问来源于stack exchange,提问作者user466663
相关产品推荐
相关产品推荐

