13

我想我的應用程序的一個區域內,我的MVC應用程序的默認URL設置爲一個視圖。該地區被稱爲「常見」控制器「」和視圖「指數」。ASP.NET MVC默認網址查看

我已經嘗試將web.config的表單部分中的defaultUrl設置爲「〜/ Common/Home/Index」,但沒有成功。

我還試圖映射在Global.asax的新路線,即:

routes.MapRoute(
     "Area", 
     "{area}/{controller}/{action}/{id}", 
     new { area = "Common", controller = "Home", action = "Index", id = "" } 
    ); 

再次,無濟於事。

+1

在進一步的調查(如果你通過添加VS該地區的存在),看來要求正在被引導到正確的控制器(即MyApp.Areas.Common.Controllers.HomeController)有或沒有您建議的更改。但是,在這兩種情況下,ViewEngine只搜索〜/ Views/Home和〜/ Views/Shared文件夾,而不是以〜/ Areas/Common/Views/Home和〜/ Areas/Common/Views/Shared開頭。奇怪的是,如果我使用ActionLink創建一個頁面到相同的控制器方法(即Index()),那麼它工作正常。嗯。 – 2010-01-06 10:41:27

+0

http://stackoverflow.com/questions/2140208/how-to-set-a-default-route-to-an-area-in-mvc這可能會有所幫助。我有類似的問題。 – LiamB 2010-02-11 08:31:29

回答

12

你只列出的路線工作,如果他們明確地輸入了網址:

yoursite.com/{area}/{controller}/{action}/{id} 

什麼這條路線說的是:

如果我能有一個有效的{area}的請求,有效{controller}在該地區,並在控制器有效{action},然後將其路由那裏。

你想要的是默認該控制器如果他們只是訪問您的網站,yoursite.com

routes.MapRoute(
    "Area", 
    "", 
    new { area = "Common", controller = "Home", action = "Index" } 
); 

它說的是,如果他們不添加任何東西http://yoursite.com然後路由到以下動作:Common/Home/Index

而且,把它放在你的路由表的頂部。

確保你也讓MVC知道註冊您的應用程序有幾個方面:

把你Application_Start方法如下在Global.asax.cs文件:

AreaRegistration.RegisterAllAreas(); 
+1

對我來說,這是在根文件上搜索,而不是在該地區。 – FrenkyB 2016-06-29 10:44:14

0

你是什麼做得似乎正確。如果我猜我會說這是發生因您運行的網站的方式。在Visual Studio中,如果您在按F5時選擇了特定的視圖,那麼該視圖將成爲起始URL - 嘗試選擇Project,然後按F5?

+0

恐怕這不是問題的原因。儘管感謝您的建議。 – 2010-01-06 10:22:50

+0

這是值得一試的:D – 2010-01-06 10:43:55

7

你所要做的是:

  • 刪除缺省路由的global.asax.cs區常見

  • 添加以下航線

    //// default route map will be create under area 
    //routes.MapRoute(
    // name: "Default", 
    // url: "{controller}/{action}/{id}", 
    // defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
    //); 
    
  • 更新SecurityAreaRegistration.cs映射:

    context.MapRoute(
        "Default", 
        "", 
        new { controller = "Home", action = "Index", id = "" } 
    ); 
    
0

在Global.asax 刪除。圖路線

,並使它看起來像

public static void RegisterRoutes(RouteCollection routes) 
{ 
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 
} 

然後在該地區的yourareaAreaRegistration.cs

public override void RegisterArea(AreaRegistrationContext context) 
{ 
    //This is the key one   
    context.MapRoute("Root", "", new { controller = "Home", action = "Login" }); 

    //Add more MapRoutes if needed 
}