读取Ajax onSuccess中的HttpResponseMessage
本文关键字:HttpResponseMessage 中的 onSuccess Ajax 读取 | 更新日期: 2023-09-27 18:09:20
这是我的APIController方法-
[HttpPost]
public HttpResponseMessage Get(string url) {
string responseString = GetWebApiData(url);
HttpResponseMessage response = new HttpResponseMessage();
if (!string.IsNullOrEmpty(responseString) && responseString.ToString().IsValid()) {
response.ReasonPhrase = "Valid";
response.StatusCode = HttpStatusCode.OK;
} else {
response.ReasonPhrase = "Invalid";
response.StatusCode = HttpStatusCode.BadRequest;
}
return response;
}
这是我的ajax调用上述方法-
$.ajax({
type: "POST",
url: "http://localhost:50/api/DC/" + formData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data, textStatus, xhr) {
},
failure: function(response) {
alert(response.responseText);
},
error: function(response) {
alert(response.responseText);
}
});
我无法读取API方法返回的HttpResponseMessage。对于OK和Bad Request的条件,ajax方法的xhr中返回的状态码是204 &没有内容。我需要根据响应代码进行验证。任何帮助,请!
I tried success: function(response) too, response是undefined。
响应是204 No content
,因为您实际上没有添加任何内容。你所做的就是设置响应代码。您可以像这样向响应添加内容:
response.Content = new StringContent("Return data goes here");
或者使用Request.CreateResponse()
/CreateErrorResponse()
为您创建HttpResponseMessage
:
[HttpPost]
public HttpResponseMessage Get(string url)
{
string responseString = GetWebApiData(url);
if (!string.IsNullOrEmpty(responseString) && responseString.ToString().IsValid())
{
return Request.CreateResponse("Valid"); // I'd suggest returning an object here to be serialised to JSON or XML
}
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid");
}