4

我有一個項目(名爲Product.Api),有一些控制器用於我們的WebAPI網站。控制器位於Product.Api.Controllers的命名空間中。該項目也有其他一些幫手。這被編譯成一個庫。如何在同一IIS網站下合併MVC4網站和WebAPI網站?

我也有另一個常規的ASP.NET MVC4網站名爲Product.Web。這有控制器(名稱空間Product.Web.Controllers),模型和視圖(在其相應的文件夾中)。它也有一個Global.asax.cs它有路由信息。

當在IIS(.NET 4.5,IIS7,集成模式等)中創建站點時,我將Product.Api dll複製到bin文件夾中。 Product.Web是主要網站。

現在我想將網址http://www.product.com/api/ {Controller}/{id}映射到WebAPI內容並將http://www.product.com/ {Controller}/{動作}/{id}映射到常規MVC。

這就是我現在所擁有的是我的路線:

routes.MapHttpRoute(
       name: "DefaultApi", 
       routeTemplate: "api/{controller}/{id}", 
       defaults: new {id = RouteParameter.Optional} 
      ).Constraints["Namespaces"] = new string[] { "Product.Api.Controllers" }; 

      routes.MapRoute(
       name: "Default", 
       url: "{controller}/{action}/{id}", 
       defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } , 
       namespaces: new[] { "Product.Web.Controllers" } 
      ); 

不幸的是,當我去到一個API URL(在這種情況下,例如爲http://www.product.com/api/Tables/(甚至當我定義一個id),我得到一個HTTP 404錯誤。

http://www.product.com/Home/Index工作正常。

奇怪的是我試過的routing debugger tool和我仍然有問題。其實我從來沒有看到調試器的輸出。http://www.product.com/Home/Indexhttp://www.product.com/都顯示視圖,但一切API/*仍然顯示404.我還沒有看到調試器的任何輸出。

那麼無論如何要得到理想的效果呢?

編輯:我注意到我的global.asax.cs文件位於Product.Web命名空間。我改變它在Product命名空間,仍然沒有去。

回答

4
routes.MapHttpRoute(
       name: "DefaultApi", 
       routeTemplate: "api/{controller}/{id}", 
       defaults: new {id = RouteParameter.Optional} 
      ).Constraints["Namespaces"] = new string[] { "Product.Api.Controllers" }; 

這不適用於MapHttpRoute。

如果您想要使用另一個bin的ApiController路由,只需刪除這些約束,運行時就會自動從bin中獲取您的ApiControllers。 MapHttpRoute不會干擾你的MVC控制器,反之亦然,所以不需要約束。

或者用它來contraint您HttpRoute命名空間

routes.DataTokens["Namespaces"] = new string[] {"MyNamespace"}; 

或者使用this solution(不過這真的只是需要如果你把東西箱外。)

+0

謝謝。它不再返回404.現在,即使自定義錯誤關閉,打開調試並在web.config中設置existingResponse,我也會得到500個服務器錯誤,但沒有詳細信息。 – encee 2012-07-25 17:48:12

+1

在你的global.asax中添加這個GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;這應該會幫助你獲得更詳細的錯誤。 – 2012-07-25 18:39:04

+1

此外,請檢查您爲JSON請求獲得的響應(甚至從GlobalConfiguration.Configuration.Formatters中完全刪除XML格式化程序)。它經常窒息和吞嚥異常只發射空500. – 2012-07-25 18:41:15

-1

的MapHttpRoute廠之前調用添加的System.Web .Mvc.ControllerBuilder.Current.DefaultNamespaces.Add( 「Namespace.Full.Controllers」);

+0

問題是指'MapHttpRoute'而不是'MapRoute' – ehftwelve 2014-06-13 20:34:35