2010-12-13 201 views
0

我想在我的應用程序中創建自定義路由。ASP.NET MVC自定義路由

我在全球ASAX文件添加一條新的路徑:

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

     routes.MapRoute(
      "Profile",           // Route name 
      "{controller}/{action}/{userName}",       // URL with parameters 
      new { controller = "UserProfile", action = "Index", userName = UrlParameter.Optional } // Parameter defaults 
     ); 

     routes.MapRoute(
      "Default", // Route name 
      "{controller}/{action}/{id}", // URL with parameters 
      new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults 
     ); 
    } 

它工作正常,當我使用UserProfileController:

http://localhost:7738/UserProfile/Info/chopin

但默認路由是行不通的!

我看到這個http://localhost:7738/Blog/Info?id=2代替本http://localhost:7738/Blog/Info/2

任何人都可以幫我嗎?

謝謝l。

+0

本地主機?當真? – bevacqua 2010-12-13 17:01:42

+0

@Nico你試過這些鏈接?當真? – dotjoe 2010-12-13 17:22:46

回答

2

也許你可以固定路線:

routes.MapRoute(
     "Profile",           // Route name 
     "UserProfile/{action}/{userName}",       // URL with parameters 
     new { action = "Index", userName = UrlParameter.Optional } // Parameter defaults 
    ); 
1

你的路線本質上是一樣的!

如何獲取查詢字符串的URI?

+0

+1,'{controller}/{action}/{userName}'和'{controller}/{action}/{id}'在功能上是完全相同的。 – 2010-12-13 17:19:53

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

    routes.MapRoute(
    "UserProfile", 
    "UserProfile/{action}/{userName}", 
    new { contoller = "UserProfile", action = "Index", userName = UrlParameter.Optional } 
); 

    routes.MapRoute(
    "Default", 
    "{controller}/{action}/{id}", 
    new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
); 
}