我有一个项目(名为Product.Api
),其中有一些控制器用于我们的WebAPI站点。控制器位于名称空间Product.Api.Controllers
中。该项目还有一些其他帮手的东西。这被编译成一个库。
我还有另一个名为Product.Web
的常规ASP.NET MVC4网站。它具有控制器(在命名空间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} / {Action} / {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/Index和http://www.product.com/都显示视图,但所有api / *仍然显示404.我还没有看到调试器的任何输出。
那么无论如何都能获得理想的效果吗?
编辑:我注意到我的global.asax.cs文件位于Product.Web
命名空间中。我将其更改为Product
命名空间,但仍然没有。
答案 0 :(得分: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控制器,反之亦然,因此无论如何都不需要约束。
或者使用它来约束你的HttpRoute命名空间
routes.DataTokens["Namespaces"] = new string[] {"MyNamespace"};
或者使用this solution(但如果你把东西放在垃圾箱之外,那真的只需要。)
答案 1 :(得分:-1)
在MapHttpRoute Factory调用之前添加System.Web.Mvc.ControllerBuilder.Current.DefaultNamespaces.Add(“Namespace.Full.Controllers”);