【问题标题】:ASP.NET MVC JsonResult not returning responseText in jQuery.post fail callback functionASP.NET MVC JsonResult 未在 jQuery.post 失败回调函数中返回 responseText
【发布时间】:2016-09-29 17:17:15
【问题描述】:

我正在使用 jQuery $.post 将一些数据发布到我的控制器内的 ActionResult 方法。当控制器中抛出错误时,它应该在响应的 responseText 中返回错误消息,但它不起作用。

post 请求正在访问控制器。

似乎触发了回调函数fail。只是没有收到返回的错误消息。不知道我做错了什么?

这是 jQuery 发布数据:

var postData = ["1","2","3"];

$.post('/MyController/GetSomething', $.param(postData, true))
      .done(function (data) {
              alert('Done!');                        
      })
      .fail(function (xhr, textStatus, errorThrown) {
              alert(xhr.responseText); //xhr.responseText is empty   
      });
 });

控制器

public class MyController : BaseController { public ActionResult GetSomething(List ids) { try { GetSomeData(ids); } catch (Exception ex) { return ThrowJsonError(new Exception(String.Format("The following error occurred: {0}", ex.ToString()))); } return RedirectToAction("Index"); } } public class BaseController : Controller { public JsonResult ThrowJsonError(Exception ex) { Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest; Response.StatusDescription = ex.Message; return Json(new { Message = ex.Message }, JsonRequestBehavior.AllowGet); } }

更新 有趣的是,如果我将一些逻辑从 BaseController 移到 MyController 中,我就能得到想要的结果。

为什么会这样?

public class MyController : BaseController
    {
        public ActionResult GetSomething(List<string> ids)
        {
            try
            {
                GetSomeData(ids);
            }
            catch (Exception ex)
            {
                Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
                Response.StatusDescription = ex.Message;

                return Json(new { Message = ex.Message }, JsonRequestBehavior.AllowGet);
            }

            return RedirectToAction("Index");
        }
    }

【问题讨论】:

  • 是到达控制器还是之前报错?
  • 是的,它确实到达了控制器。如果随后在 Controller 中引发异常,则 Message 不会以 xhr.ResponseText = "" 的形式返回
  • 如果你把 alert(data.Message);在警报之前(“完成!”);发生了什么?
  • 我在这里有一些问题,GetSomeData(ids); 中的内容在此之后您重定向到索引操作,Index 中的内容以及您没有将任何数据从GetSomething 传递到index
  • @DanielVorph 当Controller中抛出异常时,我肯定是在打.fail(function (xhr, textStatus, errorThrown) { alert(xhr.responseText); //xhr.responseText is empty });函数。

标签: c# jquery asp.net-mvc


【解决方案1】:

这是因为您在 ThrowJsonError 函数中设置了无效的 StatusDescription。它有换行符,会导致 Http Header 出现意外结果。见this related question

问题被混淆了,因为您的第一个示例将StatusDescription 设置为您正在构建的新Exception 的Message 属性,该属性将包含换行符和堆栈跟踪信息,因为您调用了ex.ToString()。第二个有效,因为您只是将 StatusDescription 设置为 ex.Message 并且不包含有问题的字符

为了安全起见,您可能应该只使用相对温和的StatusDescription,因为无论如何您都不需要它(无论哪种方式,您都可以在fail() 中获得Message。

注意以下代码有效(仍然不推荐):

public ActionResult ThrowJsonError(Exception ex)
{
   Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
   Response.StatusDescription = ex.Message; // does not work
   Response.StatusDescription = ex.Message.Replace('\r', ' ').Replace('\n', ' '); // works

   return Json(new { Message = ex.Message }, JsonRequestBehavior.AllowGet);
}

【讨论】:

  • 嗯明白了。感谢您的帮助和花时间解释。
猜你喜欢
  • 2011-08-28
  • 2011-03-08
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多