ASP.NET MVC JsonResult没有在jQuery.post中返回responseText失败回调函数

时间:2016-09-29 17:17:16

标签: c# jquery asp.net-mvc

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

帖子请求正在击中控制器。

似乎触发了回调函数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");
        }
    }

1 个答案:

答案 0 :(得分:1)

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

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

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

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

fail()