2014-07-05 47 views
1

我剛將一個現有的API項目合併到另一個現有的MVC項目中。 API控制器與MVC控制器具有相同的名稱,但它們位於2個不同的名稱空間中(分別爲MyApp.Web.MyController和MyApp.API.MyController)。在同一個項目中爲MVC和API配置路由

現在,我真的不知道如何路由配置,這樣我可以訪問API控制器:(

我看到這篇文章:Mixing Web Api and ASP.Net MVC Pages in One Project和希望達到什麼樣的@Mike沃森認爲有,但我不知道該如何配置路由

這是我目前在RouteConfig.cs:

public class RouteConfig 
{ 
    public static void RegisterRoutes(RouteCollection routes) 
    { 
     routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 

     routes.MapRoute(
      name: "Default", 
      url: "{controller}/{action}/{id}", 
      defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
     ); 
    } 
} 
+1

最簡單的方式來創建新的項目與API和mvc比較。你將能夠看到如何配置 – Uriil

+0

謝謝!我添加了WebApiConfig.cs到MVC項目,並從Global.asax.cs添加了對它的調用。這似乎現在:)。 – AngieM

回答

1

看起來你已經有工作,但你應該永遠希望使用一個區域的API控制器,您可以啓用它只需添加一條附加路線。

public static class WebApiConfig 
{ 
    public static void Register(HttpConfiguration config) 
    { 
     config.Routes.MapHttpRoute(
      name: "DefaultAreaApi", 
      routeTemplate: "api/{area}/{controller}/{action}/{id}", 
      defaults: new { id = RouteParameter.Optional } 
     ); 

     config.Routes.MapHttpRoute(
      name: "DefaultApi", 
      routeTemplate: "api/{controller}/{action}/{id}", 
      defaults: new { id = RouteParameter.Optional } 
     ); 
    } 
} 


// Application_Start 

GlobalConfiguration.Configure(WebApiConfig.Register); 
AreaRegistration.RegisterAllAreas(); 
+0

好吧,不知何故,我設法得到一個行動的工作,所有其他行動返回404錯誤。所有這些操作(在同一個控制器中)在他們的舊API項目中工作。我到處看看是什麼造成的,但找不到任何東西。 – AngieM

+0

我有你在那裏展示的東西,但只有一個動作起作用。所有其他操作都會返回404 Not Found與此長消息。我很困惑。 – AngieM

+0

我發現的工作有簡單的參數(例如/ api/MyController/WorkingAction/Parameter)。 所有其他操作以404未找到(例如/ api/MyController/NotWorkingAction)結尾 – AngieM