2011-11-10 47 views
0

我試圖通過將每個區域移動到他們自己的項目中來模擬我的ASP.NET MVC應用程序。一切工作正常,直到我決定重構AreaRegistration的東西,並使用我自己的方法(這樣我也可以在我的模塊中註冊過濾器和依賴關係)。我使用反射器設法得出以下結論。單個項目中的ASP.NET MVC區域 - 重構區域註冊項目

首先,我必須對每個模塊/區域如下界面:

public interface IModule { 
    string ModuleName { get; } 
    void Initialize(RouteCollection routes); 
} 

如:

public class BlogsModule : IModule { 
    public string ModuleName { get { return "Blogs"; } } 

    public void Initialize(RouteCollection routes) { 
     routes.MapRoute(
      "Blogs_Default", 
      "Blogs/{controller}/{action}/{id}", 
      new { area = ModuleName, controller = "Home", action = "Index", 
       id = UrlParameter.Optional }, 
      new string[] { "Modules.Blogs.Controllers" } 
     ); 
    } 
} 

然後在我的Global.asax文件(Application_Start事件)我說:

// Loop over the modules 
foreach (var file in Directory.GetFiles(Server.MapPath("~/bin"), "Modules.*.dll")) { 
    foreach (var type in Assembly.LoadFrom(file).GetExportedTypes()) { 
     if (typeof(IModule).IsAssignableFrom(type)) { 
      var module = (IModule)Activator.CreateInstance(type); 
      module.Initialize(RouteTable.Routes); 
     } 
    } 
} 

然後我刪除了現有的AreaRegistration東西。到目前爲止,一切正常。當我運行我的應用程序和渲染顯示正確的URL鏈接的模塊,例如:

@Html.ActionLink("Blogs", "Index", "Home", new { area = "Blogs" }, null) 

但是當我點擊該網址會顯示錯誤的觀點。調試後,它看起來像是路由到我的博客模塊的HomeController中正確的操作。但是它會嘗試在主項目中顯示Home/Index.cshtml視圖,而不是在模塊/區域中顯示Home/Index.cshtml視圖。我猜測沿線的某處我錯過了如何告訴視圖引擎將路由URL視爲一個區域,因爲它似乎忽略了AreaViewLocationFormats(在RazorViewEngine中)。

我很感激,如果有人能告訴我我失蹤了。謝謝

回答

0

進一步重構後,看起來,視圖引擎查找區域數據令牌。因此,我更改了代碼,以在模塊的Initialize方法中添加路由,如下所示:

// Create the route 
var route = new Route("Blogs/{controller}/{action}/{id}", new RouteValueDictionary(new { area = ModuleName, controller = "Home", action = "Index", id = UrlParameter.Optional }), new MvcRouteHandler()); 

// Add the data tokens 
route.DataTokens = new RouteValueDictionary(); 
route.DataTokens["area"] = this.ModuleName; 
route.DataTokens["UseNamespaceFallback"] = false; 
route.DataTokens["Namespaces"] = new string[] { "Modules.Blogs.Controllers" }; 

// Add the route 
routes.Add(route); 

希望這有助於。