控制器继承
使用继承作为Chris评论部分中提到的可能也是解决此问题的最佳方法。如果您已经从另一个基本控制器类派生,例如ApplicationController
在你的例子中:
// ProjectA is assumed to be your "main" MVC application
public class CustomFooController : ProjectA.Controllers.FooController
{
[Route("Foo/Bar")]
public ActionResult Bar()
{
return Content("Bar");
}
}
这里的属性路由非常重要,因为您不希望现有的路由混淆您的两个控制器或忽略它们。
注册属性路由
由于您通过以下方式使用属性路由[Route]
属性在您的 ProjectB 部分中,您需要确保在RouteConfig.cs
您的 ProjectA 项目,以便它可以通过Routes.MapMvcAttributeRoutes()
方法如下所示:
public static void RegisterRoutes(RouteCollection routes)
{
// This is important to set up your Route Attributes
routes.MapMvcAttributeRoutes();
// Route declarations omitted for brevity
}
同样,如果您使用区域,则需要在相应的区域中进行配置AreaRegistration.cs
文件以及:
public override void RegisterArea(AreaRegistrationContext context)
{
// Wire up any attribute based routing
context.Routes.MapMvcAttributeRoutes();
// Area routing omitted for brevity
}
范围界定路线
最后,您要确保做的最后一件事是正确“范围”您的路由,以优先考虑您的主名称空间在RouteConfig.cs
您的主要 ProjectA 应用程序:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Foo", action = "Index", id = UrlParameter.Optional },
// This will prioritize your existing Controllers so they work as expected
namespaces: new[] { "ProjectA.Controllers"}
);
}
获取参考文献
您提到使用构建事件将 DLL 从 ProjectB 项目复制到主 ProjectA 项目中,在这种情况下应该没问题。你基本上需要some访问它的方法和一个简单的xcopy
在大多数情况下,像下面这样应该没问题:
xcopy /E /Y /S "$(ProjectName).dll" "$(SolutionDir)\ProjectA\Bin\"
把它们放在一起
如果您已正确连接所有这些步骤,您应该能够清理/重建现有的解决方案。执行此操作后,请仔细检查以确保 ProjectA 中具有适当的 DLLbin
目录 :
![enter image description here](https://i.stack.imgur.com/xhgzh.png)
如果存在,那么您就走在正确的轨道上,应该能够运行您的主应用程序并导航到~/Foo
查看以下内容:
![enter image description here](https://i.stack.imgur.com/TmJIi.png)
同样,导航至~/Foo/Bar
应该选择在其他控制器中定义的适当属性路由并提供正确的内容:
![enter image description here](https://i.stack.imgur.com/AjZTj.png)