ASP.NET Core控制器返回JSON前端JS访问属性为undefined问题咨询
问题根因
你遇到的问题本质是两次序列化导致前端拿到的是JSON格式字符串,而非可直接访问属性的JS对象:
- 后端将上游API返回的JSON反序列化后转成字符串,再用
Ok()返回时,ASP.NET Core会自动对这个字符串做二次序列化,相当于给JSON内容套了两层引号 - 前端AJAX未指定返回数据类型,jQuery不会自动把返回的字符串转成JS对象
- 额外注意:你的上游API返回的是
List<PPodcast>数组,前端不能直接访问data.titulo,需要先取数组下标对应的元素再访问属性
修复方案
后端修复(二选一即可,优先方案1更符合.NET开发规范)
方案1:返回强类型对象,让框架自动处理序列化
public async Task<IActionResult> GetPodcastLandingPortada() { List<PPodcast> ppodcastPortada = new List<PPodcast>(); using (var httpClient = new HttpClient()) { using (var response = await httpClient.GetAsync("https://localhost:44379/api/Podcast/ObtenerPodcastPortadaPrincipal")) { string apiResponse = await response.Content.ReadAsStringAsync(); ppodcastPortada = JsonConvert.DeserializeObject<List<PPodcast>>(apiResponse); } } // 直接返回集合,框架自动序列化为标准JSON,无二次序列化问题 return Ok(ppodcastPortada); }
方案2:透传上游API的JSON内容,无需反序列化
public async Task<IActionResult> GetPodcastLandingPortada() { using (var httpClient = new HttpClient()) { using (var response = await httpClient.GetAsync("https://localhost:44379/api/Podcast/ObtenerPodcastPortadaPrincipal")) { string apiResponse = await response.Content.ReadAsStringAsync(); // 直接返回原始JSON,指定响应类型,避免二次序列化 return Content(apiResponse, "application/json"); } } }
前端修复
修正AJAX配置,移除无效参数,指定JSON返回类型:
function _getPortadaPrincipal() { let ruta = '/podcast/GetPodcastLandingPortada'; $.ajax({ type: 'GET', url: ruta, dataType: 'json', // 明确指定返回JSON,jQuery会自动转成JS对象 success: function (data) { // 后端返回的是数组,需要先取下标对应的元素再访问属性 console.log(data[0].titulo); // 注意原代码的row变量未定义,需自行遍历data数组生成对应HTML内容 $("#portadaPrincipal").html(row); console.log(data); }, error: function () { alert("Error en la carga de la Portada"); }, }); }
内容的提问来源于stack exchange,提问作者Daniel Lazarte
相关产品推荐
相关产品推荐

