是否可以使用自定义错误页面与MVC站点而不是Web API?

Ben*_*men 30 iis error-handling asp.net-mvc web-config asp.net-web-api

我有一个带有/ api文件夹的MVC项目,其中包含我的Web API控制器.我想要以下事项:

  • 我的MVC站点在发生错误时提供自定义错误页面
  • 我的Web API提供默认错误响应(包含异常和堆栈跟踪的json/xml)

在我的MVC站点的web.config中,我有一个httpErrors节点,并将errorMode设置为"Custom",以便在404s/500s/etc时我可以拥有漂亮的错误页面.在浏览MVC站点期间发生:

<httpErrors errorMode="Custom" existingResponse="Replace">
  <remove statusCode="404" subStatusCode="-1" />
  <remove statusCode="500" subStatusCode="-1" />
  <remove statusCode="403" subStatusCode="-1" />
  <error prefixLanguageFilePath="" statusCode="404" path="Content\notfound.htm" responseMode="File" />
  <error statusCode="500" path="/Errors" responseMode="ExecuteURL" />
  <error statusCode="403" path="/Errors/Http403" responseMode="ExecuteURL" /></httpErrors>
Run Code Online (Sandbox Code Playgroud)

但是,使用该配置,API将在发生错误时提供自定义错误页面,而不是具有异常/堆栈跟踪的json/xml(这是所需的行为).

有没有办法将自定义错误配置为仅应用于我的MVC站点而不是Web API?这篇博客说没有(http://blog.kristandyson.com/2012/11/iis-httperrors-aspnet-web-api-fully.html),但我想知道是否有其他人找到了工作自该博客发布以来.

我想如果没有,我可以为我的Web API项目创建一个单独的项目/程序集.这将允许我分别为MVC和Web API配置httpErrors,但我不想创建另一个项目,所以我还有另一个web.config来配置.

Ben*_*men 67

好吧,经过将近一年的时间让这个问题腌制后,我又给了它一个机会.这是web.config魔术,它让我得到了我想要的东西:

<!-- inside of <configuration> to allow error
    responses from requests to /api through -->
<location path="api">
    <system.webServer>
      <validation validateIntegratedModeConfiguration="false" />
      <httpErrors errorMode="DetailedLocalOnly" existingResponse="PassThrough" >
        <clear/>
      </httpErrors>
    </system.webServer>
</location>

<!-- original httpErrors, inside of <location path="." inheritInChildApplications="false">
 to serve custom error pages when the MVC site returns an error code -->
<httpErrors errorMode="Custom" existingResponse="Replace">
      <remove statusCode="400" subStatusCode="-1" />
      <remove statusCode="404" subStatusCode="-1" />
      <remove statusCode="500" subStatusCode="-1" />
      <remove statusCode="403" subStatusCode="-1" />
      <error statusCode="400" prefixLanguageFilePath="" path="Content\notfound.htm" responseMode="File"/>
      <error prefixLanguageFilePath="" statusCode="404" path="Content\notfound.htm" responseMode="File" />
      <error statusCode="500" path="/errors" responseMode="ExecuteURL" />
      <error statusCode="403" path="/errors/http403" responseMode="ExecuteURL" />
    </httpErrors>
Run Code Online (Sandbox Code Playgroud)

这里发生的关键是<location>节点允许您覆盖在不太具体的路径上进行的设置.因此,虽然我们对path ="."有errorMode ="Custom",但我们会覆盖我们的Web API与<location path="api">节点的路径以及其中的httpErrors配置.

我以前见过节点,但直到现在我才知道这是他们的目的.本文详细介绍了IIS/.NET的配置继承模型,我发现这些模型非常有用:http://weblogs.asp.net/jongalloway/10-things-asp-net-developers-should-know-about织网,配置继承和-覆盖

  • 非常感谢 - 我一直在用头撞墙试图解决这个问题,只是没有想到这个简单的解决方案! (2认同)
  • 这最终是允许一切按需工作的解决方案. (2认同)