在ASP .NET MVC3上使用HTML而不是JSON进行IIS响应

kok*_*sda 12 error-handling json asp.net-mvc-3

该主题是自我解释的.我有开发人员和生产环境.开发者环境 是我的localhost机器.我在contolers中有动作方法,当出现错误(出错或逻辑不一致)并返回Json-answer时,将响应状态代码设置为500.我的常用方法如下:

[HttpPost]
public ActionResult DoSomething(int id)
{
    try
    {
         // some useful code
    }
    catch(Exception ex)
    {
         Response.StatusCode = 500;
         Json(new { message = "error" }, JsonBehaviour.AllowGet)
    }
}
Run Code Online (Sandbox Code Playgroud)

在客户端生产环境.当发生这样的错误时,ajax.response看起来像一个HTML代码,而不是预期的JSON.

考虑一下:

<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>
Run Code Online (Sandbox Code Playgroud)

过滤器上下文不是一个选项.我认为这是某种IIS或web.config问题.

解决方案: 我们决定TrySkipIisCustomErrors在Global.asax中添加BeginRequest,它解决了我们应用程序中每个方法的问题.

Dar*_*rov 12

我想IIS正在提供一些友好的错误页面.您可以尝试通过TrySkipIisCustomErrors在响应上设置属性来跳过此页面:

catch(Exception ex)
{
     Response.StatusCode = 500;
     Response.TrySkipIisCustomErrors = true;
     return Json(new { message = "error" }, JsonBehaviour.AllowGet)
}
Run Code Online (Sandbox Code Playgroud)

  • 一点都不。这不是黑客攻击。友好的错误页面是 ASP.NET 中内置的功能。如果您不喜欢它们,请不要使用它们。但是,如果您决定使用它们,您应该了解后果(您不能使用自定义响应设置错误状态代码),而无需明确告知 IIS。 (2认同)