最近使用ASP.NET MVC 4.0,发现虽然可以自定义路由、视图的规则,但相对还是比较死板,
全部的Contorl都放一起,全部的Views都放一起,功能多的时候岂不乱七八糟,比如想按业务模块来划分功能代码,
ASP.NET MVC 2.0以后提供了Areas区域功能,可以让我们对代码进行分区分块,但这样的分区模式也还是不够灵活
呵,遂上网爬到自定义视图的方法,可惜自定义RazorViewEngine过程中,虽然运行时是成功的,开发中遇到各式各样的问题却不得而解
比如,新建一个CustomViewEngine.cs文件:
1 public class CustomViewEngine : RazorViewEngine 2 { 3 public CustomViewEngine() 4 { 5 ViewLocationFormats = 6 new string[] 7 { 8 "~/Views/{1}/{0}.cshtml", 9 "~/Views/{1}/Shared/{0}.cshtml", 10 "~/Views/Shared/{0}.cshtml" 11 }; 12 AreaViewLocationFormats = new[] 13 { 14 "~/Areas/{2}/Views/{1}/{0}.cshtml", 15 "~/Areas/{2}/Views/Shared/{0}.cshtml", 16 17 "~/Areas/Apps/{2}/Views/{1}/{0}.cshtml", 18 "~/Areas/ERP/{2}/Views/{1}/{0}.cshtml", 19 "~/Areas/OA/{2}/Views/{1}/{0}.cshtml", 20 21 "~/Areas/Apps/{2}/Views/Shared/{0}.cshtml", 22 "~/Areas/ERP/{2}/Views/Shared/{0}.cshtml", 23 "~/Areas/OA/{2}/Views/Shared/{0}.cshtml" 24 }; 25 26 PartialViewLocationFormats = ViewLocationFormats; 27 AreaPartialViewLocationFormats = AreaViewLocationFormats; 28 } 29 }
然后,修改Global.asax.cs文件:
1 protected void Application_Start() 2 { 3 AreaRegistration.RegisterAllAreas(); 4 WebApiConfig.Register(GlobalConfiguration.Configuration); 5 FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 6 RouteConfig.RegisterRoutes(RouteTable.Routes); 7 BundleConfig.RegisterBundles(BundleTable.Bundles); 8 9 ViewEngines.Engines.Clear(); // 清除原MVC视图引擎规则 10 ViewEngines.Engines.Add(new CustomViewEngine()); // 使用自定义视图引擎规则 11 }
经过上述改造,自定义RazorViewEngine视图引擎运行是成功了
但在控制器中“添加视图”位置就不对,用ReShaper添加也不对,添加后得手工再转移视图文件的位置,而“转到视图”功能则完全没的用了,提示“找不到匹配的视图”。
所以这样的自定义视图法,除了运行时成功和自己看着爽,VS开发工具和ReShaper插件均却告定位失败,
一句话总结:ASP.NET MVC的RazorViewEngine视图引擎自定义,真是让人哭笑不得,用之不爽,弃之可惜啊!