Ajax调用ASP.NET Core Web API返回undefined且无错误的问题排查求助
Ajax调用ASP.NET Core Web API返回undefined且无错误的问题排查求助
我现在碰到一个很费解的问题:在我的ASP.NET Core MVC项目中,通过HttpClient调用外部API完成用户注册流程,后端所有环节看起来都正常跑通了,但前端Ajax拿到的响应却一直是undefined,而且完全没有错误提示,实在找不到问题所在。
先把整个场景和相关内容理清楚:
- Web端:从页面表单通过Ajax请求HomeController的
KullaniciKayitAction,这个Action会通过服务层调用外部API - 外部API:
https://localhost:44397/api/KullaniciKaydet/KullaniciKayit端点用Postman测试完全正常,能正确返回Kullanici对象数据 Kullanici模型在Web项目和API之间是共享的,结构完全一致
相关代码片段
1. Web项目的HomeController Action
[HttpPost] public async Task<Kullanici> KullaniciKayit(Kullanici model) { var result = await _kullaniciService.KullaniciKayit(model); return Ok(result); // 这里明确返回了Ok包装的结果 }
2. 前端Ajax请求代码
$.ajax({ url: "/Home/KullaniciKayit", type: "POST", contentType: "application/json", data: JSON.stringify(model), success: function (data) { console.log("Gelen veri:", data); // 这里始终拿到undefined alert("Kayıt başarılı"); }, error: function (xhr) { console.error("Hata:", xhr.responseText); } });
3. Web项目的服务层(调用外部API的逻辑)
public async Task<Kullanici> KullaniciKayit(Kullanici model) { var json = JsonConvert.SerializeObject(model); var content = new StringContent(json, Encoding.UTF8, "application/json"); var response = await _httpClient.PostAsync("api/KullaniciKaydet/KullaniciKayit", content); if (response.IsSuccessStatusCode) { var responseBody = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<Kullanici>(responseBody); } else { throw new HttpRequestException($"API Error: {response.StatusCode}"); } }
已经排查过的内容
- 用Postman测试外部API,能正确返回预期的Kullanici格式数据
- Web端Controller确实写了
return Ok(result)的返回逻辑 - 外部API返回的响应头中
Content-Type是application/json - 浏览器Network标签显示请求是成功状态(200),但响应体是空的
{} - 前端
console.log(data)输出明确是undefined
有没有大佬能帮我定位下问题出在哪呀?
内容来源于stack exchange
相关产品推荐
相关产品推荐

