服务器未返回状态代码为400(.net)的JSON [英] Server not returning JSON with status code 400 (.net)

查看:116
本文介绍了服务器未返回状态代码为400(.net)的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到一个奇怪的问题,就是在出错时返回带有json的400状态代码.

I've got a weird problem with returning a 400 status code with json on error.

在我的控制器中,我有类似的东西:

In my controller, I've got something like:

if(!ModelState.IsValid)
{
    string[] errors = ModelState.Values
                            .SelectMany(x => x.Errors)
                            .Select(x => x.ErrorMessage).ToArray<string>();

    Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
    return Json(new { success = false, errors = errors }, JsonRequestBehavior.DenyGet);
}

这在我的开发机器上正常工作.我可以在ajax错误方法中得到错误.但是当我部署到服务器时,服务器不再返回JSON.我总是得到responseText而不是responseJSON.如果我删除Response.StatusCode,它将正常工作.

This works fine on my development machine. I can get the errors in the ajax error method. But when I deploy to the server, the server doesn't return the JSON anymore. I always get responseText instead of reponseJSON. If I remove the Response.StatusCode it works fine.

这使我相信,当我设置Response对象的StatusCode属性时,该函数会返回".这有发生在其他人身上吗?有人知道解决方案吗?

This leads me to believe that the function 'returns' when I set the Response object's StatusCode property. Has this happened to anyone else? Anyone know the solution?

推荐答案

我终于弄清楚了问题所在.将其发布在此处,以作为其他可能为此扯头发的人的答案.

I finally figured out what the problem is. Posting this here as an answer for anyone else who may be pulling their hair out over this.

设置以下内容:

Response.TrySkipIisCustomErrors = true;

请确保在设置状态代码之前 设置了此设置.我还弄清楚了为什么它在我的本地计算机上而不是在测试/通用服务器上工作.在我的web.config中,CustomErrors设置为 Off ,而在服务器上,它设置为 On .

Make sure that this is set before you set the status code. I also figured out why it was working on my local machine and not on the test/uat servers. In my web.config, the CustomErrors was set to Off whereas on the servers it was set to On.

好像服务器' returns '一样,只要看到BadRequest状态代码被写入Response.

Seems like the server 'returns' as soon as it sees a BadRequest status code being written to the Response.

这篇关于服务器未返回状态代码为400(.net)的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆