Asp.net-Mvc

是否可以將自定義錯誤頁面與 MVC 站點一起使用,但不能在 Web API 中使用?

  • September 17, 2013

我有一個帶有 /api 文件夾的 MVC 項目,其中包含我的 Web API 控制器。我想要以下東西:

  • 我的 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 需要配置。

好吧,在讓這個問題pickle近一年之後,我又試了一次。這是讓我得到我想要的東西的 web.config 魔法:

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

&lt;!-- original httpErrors, inside of &lt;location path="." inheritInChildApplications="false"&gt;
to serve custom error pages when the MVC site returns an error code --&gt;
&lt;httpErrors errorMode="Custom" existingResponse="Replace"&gt;
     &lt;remove statusCode="400" subStatusCode="-1" /&gt;
     &lt;remove statusCode="404" subStatusCode="-1" /&gt;
     &lt;remove statusCode="500" subStatusCode="-1" /&gt;
     &lt;remove statusCode="403" subStatusCode="-1" /&gt;
     &lt;error statusCode="400" prefixLanguageFilePath="" path="Content\notfound.htm" responseMode="File"/&gt;
     &lt;error prefixLanguageFilePath="" statusCode="404" path="Content\notfound.htm" responseMode="File" /&gt;
     &lt;error statusCode="500" path="/errors" responseMode="ExecuteURL" /&gt;
     &lt;error statusCode="403" path="/errors/http403" responseMode="ExecuteURL" /&gt;
   &lt;/httpErrors&gt;

這裡發生的事情的癥結在於該&lt;location&gt;節點允許您覆蓋在不太具體的路徑上所做的設置。因此,雖然我們為 path="." 設置了 errorMode=“Custom”,但我們使用&lt;location path="api"&gt;節點覆蓋了我們的 Web API 路徑以及其中的 httpErrors 配置。

我以前見過節點,但直到現在我才意識到這是它們的目的。本文更詳細地介紹了 IIS/.NET 的配置繼承模型,我發現它非常有用:http ://weblogs.asp.net/jongalloway/10-things-asp-net-developers-should-know-about -web-config-inheritance-and-overrides

引用自:https://stackoverflow.com/questions/18858925