2014-02-10 23 views
1

我的解決方案有很深的文件夾結構相匹配的業務結構,深層去3-4個等級,如:在ASP.NET MVC中強加深層業務結構的選項?

\Franchises 
    \Regionals 
     \Billing 
     \Monthly 
     \... 
     \... 
     \... 
     \... 
    \... 
    \... 
\... 
\... 

域中的文件夾結構,流程和報表項目與這一結構一致。

MVC是一種痛苦。默認情況下只允許1級深:

\Controllers\BlahBlah 

使用MVC領域,我可以得到2級深(klutzily增加兩個文件夾的路徑):

\Areas\Franchises\Controllers\BlahBlah 

這是隔靴搔癢,以反映該業務的深層結構。

我對將WebUI垂直分割爲多個項目猶豫不決,因爲這需要進一步的整合工作,而且似乎只是爲了施加業務結構而矯枉過正。

是否有強制任意文件夾級別到MVC項目的方法?我應該手動硬編碼所有的控制器路由嗎?

+0

見http://mvccoderouting.codeplex.com –

回答

2

它不一定是映射每個控制器physycal文件夾路徑,你可以組織你的文件夾結構,只要你想,但如果你想自動映射路由到所有的樹子 - 你可以在你Controllers文件夾探索子命名和自動映射它給你的路線,沒有任何硬編碼,還有我的解決方案:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Reflection; 
using System.Web.Mvc; 
using System.Web.Routing; 

namespace WebApplication2 
{ 
    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 } 
      ); 
      routes.MapAllRoutesToFolders(); 
     } 
    } 

    public static class RouteExtensions 
    { 
     public static void MapAllRoutesToFolders(this RouteCollection routes) 
     { 
      const string commonControllerUrl = "{controller}/{action}/{id}"; 
      var folderMappings = GetSubClasses<Controller>() 
       .Select(x => new 
       { 
        Path = string.Join("/", x.FullName 
         .Split(".".ToCharArray(), StringSplitOptions.RemoveEmptyEntries) 
         .SkipWhile(c => c != "Controllers")) 
         .TrimStart("/Controllers/".ToCharArray()) 
         .Replace(x.Name, string.Empty), 
        Name = x.Name.Replace("Controller", string.Empty) 
       }); 
      var controllerPaths = 
       folderMappings.Where(s => !string.IsNullOrEmpty(s.Path)) 
        .Select(x => new 
        { 
         ControllerName = x.Name, 
         Path = x.Path + commonControllerUrl 
        }); 
      foreach (var controllerPath in controllerPaths) 
      { 
       routes.MapRoute(null, controllerPath.Path, new { controller = controllerPath.ControllerName, action = "Index", id = UrlParameter.Optional }); 
      } 
     } 

     private static IEnumerable<Type> GetSubClasses<T>() 
     { 
      return Assembly.GetCallingAssembly().GetTypes().Where(
       type => type.IsSubclassOf(typeof(T))).ToList(); 
     } 
    } 
} 

在這種情況下,你的文件夾結構應該是這樣的:

enter image description here

之後,你可以在瀏覽器中檢查:

enter image description here

+0

歡呼聲中,我會像這樣的東西去了。 –