ASP.NET Core控制器重定向异常:响应200但页面未更新且报JSON错误
问题根源与解决方案
你遇到的这个问题其实很典型——前端用异步请求(比如AJAX/Fetch)调用了后端的Attach接口,但后端返回的是重定向后的HTML页面,而前端代码期望接收JSON格式的数据,所以当它解析HTML开头的<符号时,就抛出了SyntaxError: Unexpected token < in JSON at position 0,而且异步请求不会自动触发浏览器页面跳转,这就是页面没更新的原因。
为什么RedirectToAction在这里不起作用?
RedirectToAction本质是返回一个302重定向响应,浏览器收到后会自动请求目标URL(也就是Story/Index)并返回200的HTML页面。但如果是异步请求,浏览器不会自动跳转到新页面,而是把这个HTML内容直接返回给前端JS代码,JS尝试把HTML解析成JSON,自然就报错了。
解决方法(推荐方案)
后端返回一个包含跳转地址的JSON,让前端主动执行页面跳转:
- 修改
LocationController的Attach方法:
[HttpPost, ActionName("Attach")] public IActionResult Attach([FromBody]List<Location> locations) { Story targetStory=TempData.Get<Story>("tstory"); if(targetStory!=null && locations!=null) { var slocs=this.context.StoryLocations.Where(sloc=>sloc.StoryId==targetStory.Id); this.context.RemoveRange(slocs); this.context.SaveChanges(); foreach(Location loc in locations) { this.context.StoryLocations.Add(new StoryLocation{LocationId=loc.Id,StoryId=targetStory.Id}); } this.context.SaveChanges(); } // 返回包含跳转URL的JSON,而不是重定向 return Json(new { redirectUrl = Url.Action("Index", "Story") }); }
- 前端请求成功后,拿到跳转地址并执行页面跳转:
比如用jQuery的写法:
// 假设locationsData是你要提交的数组 $.ajax({ url: '/Location/Attach', method: 'POST', contentType: 'application/json', data: JSON.stringify(locationsData), success: function(response) { if (response.redirectUrl) { window.location.href = response.redirectUrl; } }, error: function(err) { console.error('请求出错:', err); } });
或者原生Fetch API的写法:
fetch('/Location/Attach', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(locationsData), }) .then(response => response.json()) .then(data => { if (data.redirectUrl) { window.location.href = data.redirectUrl; } }) .catch(error => console.error('错误:', error));
备选方案(不推荐,仅作参考)
如果一定要后端触发跳转,那你需要把前端请求改成普通表单提交,而不是异步请求。但这样的话,你需要修改后端的参数绑定(因为表单提交的是表单数据,不是JSON):
- 去掉
[FromBody],改用[FromForm](或者直接让模型绑定自动处理) - 前端用
<form>标签提交,而不是JS异步请求
不过这种方式会导致页面刷新,用户体验不如异步请求后主动跳转好。
另外提一句,你的StoryController里的Test方法有个小笔误,return test;应该改成return "test";,不然会编译报错哦。
内容的提问来源于stack exchange,提问作者Bercovici Adrian
相关产品推荐
相关产品推荐

