0

我必须做一个“hack-around”,让简单的路由按照我的需要工作。

site.com/Event   <--- controller = Event, action = Index

site.com/Event/{id}   <--- controller = Event, action = Details

site.com/About   <--- using default router settings

当前代码:

routes.MapRoute(
     name: "Event",   // Route name
     url: "Event",    // URL with parameters
     defaults: new { controller = "Event", action = "Index" } // Parameter defaults

 );

routes.MapRoute(
     name: "EventID", // Route name
     url:  "Event/{id}", // URL with parameters
     defaults:  new { controller = "Event", action = "Details", 
                      id = UrlParameter.Optional } // Parameter defaults

);

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

有没有更好的方法来编写 Event 和 Event/{id} .. ?

更新 - 工作代码

{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapHttpRoute(
    name: "WebDefaultApi",// renamed WebDefaultApi to avoing unique name conflict in API DefaultApi
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

routes.MapRoute(
    "Details",
    "{controller}/{id}",
    new { controller = "Event", action = "Details" },
    new { id = @"^\d+$" }
);


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

1 回答 1

3

使 Id 成为必需的整数。此外,由于这是更具体的,所以它是第一个。

routes.MapRoute(
                "Details",
                "{controller}/{id}",
                new { controller = "Event", action = "Details" },
                new { id = @"^\d+$" }
            );

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

此外,如果您只想将此路由应用于特定控制器,则可以限制:

routes.MapRoute(
                "Details",
                "{controller}/{id}",
                new { controller = "Event", action = "Details" },
                new { id = @"^\d+$", controller= @"(event|news|resources)" }
            );
于 2013-08-12T16:17:20.517 回答