[英]How to send success and error messages to jQuery AJAX call from a webmethod
我正在使用 jQuery AJAX 從 aspx 頁面調用 asp.net webform 的 webmethod。 當 webmethod 遇到異常時,我會拋出 HttpResponseException 異常。 我不確定返回成功消息的最佳方式是什么。 在 Web API 中,我會返回 ApiController.Created(HttpStatusCode) 或 Ok(200)。 但是我在 webmethod 上看不到這樣的選項。 在 AJAX 調用中,我必須相應地處理成功和錯誤。 以下是我的代碼:
[WebMethod()]
public async Task<IHttpActionResult> ProcessData(CustomerData customerData)
{
try
{
HttpClient client = new HttpClient();
HttpResponseMessage resp = await client.PostAsync(<data>);
if (resp.IsSuccessStatusCode)
{
string result = await resp.Content.ReadAsStringAsync();
return ???;//how to send success message?
}
else
{
string reasonAndStatusCode = resp.StatusCode + "; " + resp.ReasonPhrase;
string errorMessage = "Method Name: ProcessData." +
"Did not process customer data." +
"Status Code and Reason: " +
reasonAndStatusCode;
HttpResponseMessage error = GenerateError(resp.StatusCode, errorMessage.ToString());
throw new HttpResponseException(error);
}
}
catch (Exception ex)
{
HttpResponseMessage error = GenerateError(HttpStatusCode.InternalServerError,
errorMessage.ToString());
throw new HttpResponseException(error);
}
}
您可以使用 HttpContext Current 靜態對象更改響應狀態代碼。
例如,如果您要發送 404 狀態代碼,請參閱下面的代碼。
HttpContext.Current.Response.StatusCode = (int)HttpStatusCode.NotFound;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.