You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MVC控制器Action无法返回JSON响应问题求助

解决MVC控制器Action返回JSON响应失败的问题

嘿,我仔细瞅了你的代码,发现问题出在返回JsonResult的语法上啦!

你的代码问题所在

你现在的返回语句把JsonRequestBehavior.AllowGet放到了匿名对象的属性里,这是错误的写法:

return Json(new { success = true, response = "File uploaded.", JsonRequestBehavior.AllowGet }); 

这种写法会让JsonRequestBehavior.AllowGet变成返回对象的一个多余属性,而不是告诉MVC允许POST请求获取JSON响应的关键参数。这会导致两个问题:一是返回的JSON结构完全不符合预期,二是MVC默认会阻止POST请求获取JSON响应(防止JSON劫持风险),自然前端拿不到正确结果。

修正后的代码

正确的写法是把匿名对象作为第一个参数,JsonRequestBehavior.AllowGet作为第二个参数单独传递给Json方法:

return Json(new { success = true, response = "File uploaded." }, JsonRequestBehavior.AllowGet);

额外排查建议

  • 可以给Action加个异常捕获,方便排查上传过程中可能出现的错误:
    try
    {
        Homes thishomes= _db.Homes.FirstOrDefault(t => t.Id == id); 
        FileUploader fileupload = new FileUploader(); 
        fileupload.PostIt(file.InputStream); 
        return Json(new { success = true, response = "File uploaded." }, JsonRequestBehavior.AllowGet);
    }
    catch(Exception ex)
    {
        return Json(new { success = false, response = $"上传失败:{ex.Message}" }, JsonRequestBehavior.AllowGet);
    }
    
  • 前端也要配合处理,比如用jQuery的$.ajax时,记得设置dataType: "json",确保能正确解析返回的JSON内容。

内容的提问来源于stack exchange,提问作者Em Jay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:45:04