把asp.net mvc5 controller 单独放置在一个项目实例

把asp.net mvc5 controller 单独放置在一个项目实例

Posted By : 蓝狐
Updated On : 2015-06-26

昨天开发蓝软件工作室官方网站的手机炫版的时候是新建的一个mvc项目,有个不好的地方就是在原来PC的MVC项目中的Controller也要拷贝到炫版的项目中,也就是以后维护两套一样的Controller代码。于是我想能不能把这个asp.net mvc5 controller 单独放置在一个项目,这们PC和炫版的MVC Web项目都引用Controller所在的dll就可以了。经过我的实验要实现这个也很简单,今天我使用VS2013写一个demo。下面请看我的步骤:

一、创建一个MVC5 Web项目

使用VS2013创建一个Web项目lanhuCMS.Web,选择模板为MVC。这时VS2013自动添加MVC5相关的类库和模板到新的项目。在添加的项目中把原来的Controllers文件夹删除了,如下图:

二、创建一个放MVC5 Controller的类库项目

选中解决方案添加一个类库项目lanhuCMS.Infrastructure,并要项目的根目录添加一个Controllers的文件夹,如下图:

接下来为项目lanhuCMS.Infrastructure添加MVC5相关的程序包,这里要注意要使用nuget程序包管理器控制台安装MVC5类库才能安装与lanhuCMS.Web项目一样MVC类库版本,不然版本不一致会报错。如果你已经安装了高于或者低于lanhuCMS.Web项目的MVC版本,也可以解决。具体看我写的文章:安装旧版本NuGet程序包到项目的方法

如果没有安装过MVC则按照下面步骤:

在NuGet程序包管理器控制台在默认项目选中项目“lanhuCMS.Infrastructure”输入“Install-package Microsoft.AspNet.Mvc -Version 5.0.0.0
”,然后回车。如下图:

在Controller文件夹中添加一个HomeController类。

  1. using System;
  2. using System.Collections.Generic;
  3. using System.linq;
  4. using System.Text;
  5. using System.Web.Mvc;
  6. namespace lanhuCMS.Infrastructure.Controllers
  7. {
  8. public class HomeController : Controller
  9. {
  10. public ActionResult Index()
  11. {
  12. return View();
  13. }
  14. public ActionResult About()
  15. {
  16. ViewBag.Message = "关于我们";
  17. return View();
  18. }
  19. public ActionResult Contact()
  20. {
  21. ViewBag.Message = "联系我们";
  22. return View();
  23. }
  24. }
  25. }

三、在Web项目中添加Controller类库引用

在项目lanhuCMS.Web中添加对项目lanhuCMS.Infrastructure引用。如下图:

最后,在RouteConfig中注册路由是指定Controller的命名空间,如下:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6. using System.Web.Routing;
  7. namespace lanhuCMS.Web
  8. {
  9. public class RouteConfig
  10. {
  11. public static void RegisterRoutes(RouteCollection routes)
  12. {
  13. routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
  14. routes.MapRoute(
  15. name: "Default",
  16. url: "{controller}/{action}/{id}",
  17. defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
  18. namespaces: new string[] { "lanhuCMS.Infrastructure.Controllers" }
  19. );
  20. }
  21. }
  22. }

最终查看Home/Index的结果如下图:

四、总结

把asp.net mvc5 controller 单独放置在一个项目有它的许多优点比如可以在多个项目中复用这些代码,易编维护等等。但是也有一些不好地方,比如不能通过右键从Controller的Action跳转到对应的视图,也不能从一个视图通过右键跳到到对应的Action方法中。具体你要根据实际情况灵活的选择。

原文地址:https://www.cnblogs.com/sishahu/p/14148506.html