IIS 按照指示返回默认错误 HTML 而不是 JSON

IIS returning default Error HTML instead of JSON, as instructed

我为我的 ASP.NET MVC 项目中的某些端点自定义了 Attribute,指示服务器 return 一个 JSON 对象,而不是处理错误通常的方式。属性如下所示:

public class AjaxErrorHandler : FilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAjaxRequest())
        {
            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
            filterContext.HttpContext.Response.StatusDescription =
                filterContext.Exception.Message.Replace('\r', ' ').Replace('\n', ' ');
            filterContext.Result = new JsonResult
            {
                Data = new { errorMessage = filterContext.Exception.Message }
            };
        }
    }
}

每当我在本地调试解决方案时,它都能正常工作,return出现以下错误:

{"errorMessage":"Error message goes here"}

但是当我将解决方案部署到我的生产服务器时,服务器始终 return 如下 HTML:

 #content{margin:0 0 0 2%;position:relative;}
 .content-container{background:#FFF;width:96%;margin-top:8px;padding:10px;position:relative;}
 -->
 </style>
 </head>
 <body>
 <div id = "header" >< h1 > Server Error</h1></div>
 <div id = "content" >
     < div class="content-container"><fieldset>
 <h2>500 - Internal server error.</h2>
 <h3>There is a problem with the resource you are looking for, and it cannot be displayed.</h3>
 </fieldset></div>
 </div>
 </body>
 </html>

我在这里缺少 Web 项目的什么配置,以使服务器遵守对 return JSON 对象的指令?

我以前在 IIS 上见过这个。

根据记忆,你可以试试这个:

  • 打开 IIS 管理器
  • Select 有问题的网站
  • 双击错误页面图标
  • 点击右侧的编辑功能设置
  • 将设置更改为远程请求的本地和自定义错误页面的详细错误
  • 重试该网站

我想这就是我过去绕过它的方式