繁体   English   中英

带有json内容类型的jquery ajax发布以HTML形式返回错误请求

[英]jquery ajax post with json content type returning bad request as HTML

我有以下示例代码可在我的本地开发环境中使用,但是当发布到使用HTTPS并使用.NET绑定的javascript和ELMAH进行错误记录的实时环境中时,此代码将无法正常工作。

我得到的不是HTML内容响应,而是带有responseText “ Bad Request”和没有responseJSON属性的HTML内容响应,因此此代码导致JavaScript错误。

有谁知道为什么内容类型会改变? 大概是因为这是在实时环境中,响应码为400? 但我不确定这是怎么回事。

控制器:

        public JsonResult JsonModelErrorResult()
        {
            Response.StatusCode = 400;
            var errors = ModelState.Values.SelectMany(m => m.Errors);
            return Json(errors);
        }

        [HttpPost]
        public ActionResult GetData()
        {
...
            if (results != null && results.Any())
            {
                return Json(result, JsonRequestBehavior.AllowGet);
            }
            else
            {
                ModelState.AddModelError("SearchResults", "No results found");
                return this.JsonModelErrorResult();
            }
        }

使用Javascript:

$.ajax("/Controller/GetData/", {
                dataType: "json",
                type: "POST",
                contentType: "application/json"
            })
            .done((result) => {
            })
            .fail((xhr) => {
                setTimeout(() => {
                    this.errors(xhr.responseJSON);
                }, 200);
            })
            .always(() => {
            });

更新:

当我在Chrome中查看请求的响应时,这是响应头:

HTTP/1.1 400 Bad Request
Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache
Content-Type: text/html
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNetMvc-Version: 4.0
X-AspNet-Version: 4.0.30319
Persistent-Auth: true
X-Powered-By: ASP.NET
Date: Thu, 03 Jul 2014 12:08:23 GMT
Content-Length: 11

并且从ajax调用返回的值是一个Jquery jqXHR对象,其responseText属性为"Bad Request" ,内容类型为"text/html"

更新2:这是我的web.config中的自定义错误设置

<customErrors mode="RemoteOnly" defaultRedirect="~/Error">
  <error statusCode="401" redirect="~/Error/NotAuthorised" />
  <error statusCode="403" redirect="~/Error/NotAuthorised" />
  <error statusCode="404" redirect="~/Error/NotFound" />
</customErrors>

在测试时,我将模式更改为“关闭”,但是在IIS8的实时环境中不起作用,也许我错过了一些需要更新的内容,以便IIS正确执行此操作或defaultRedirect="~/Error">是否也应该删除? 但是添加行Response.TrySkipIisCustomErrors = true; 进入JsonModelErrorResult代码已停止了此content / html错误,并返回了“错误请求”行。

在设置Response.StatusCode添加以下代码行:

Response.TrySkipIisCustomErrors = true;

这告诉IIS不要拦截请求并使用其自己的错误页面。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM