asp.net-mvc – 是否可以使用自定义错误页面与MVC网站,但不是Web API?

我有一个包含我的Web API控制器的/ api文件夹的MVC项目。我想要以下事情:

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

在我的MVC网站的web.config中,我有一个httpErrors节点,并将errorMode设置为“自定义”,以便在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>

然而,使用该配置,当发生错误时,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进行配置。

解决方法

好吧,经过近一年的这个问题腌制,我再给他一个镜头。这是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>

这里发生的一个关键在于< location>节点允许您覆盖在较不具体路径上进行的设置。所以当我们对path =“。”的errorMode =“Custom”时,我们用< location path =“api”>来覆盖我们的Web API的路径。节点和其中的httpErrors配置。

以前我看过节点,但是我并没有明白这是他们到目前为止的目的。本文详细介绍了IIS / .NET的配置继承模型,我发现非常翔实:http://weblogs.asp.net/jongalloway/10-things-asp-net-developers-should-know-about-web-config-inheritance-and-overrides

相关文章

这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识...
Some samples are below for ASP.Net web form controls:(fr...
问题描述: 对于未定义为 System.String 的列,唯一有效的值...
最近用到了CalendarExtender,结果不知道为什么发生了错位,...
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence cha...