开发者

How to define routes in more than one location?

Is it possible to define routes in various parts of a website.

Example, if I wanted to break functionality of my web开发者_如何学Gosite out into modules, and each module would define the routes it needs.

Is this possible? How?


Consider using ASP.NET MVC's built-in Areas.

An "Area" is essentially your module, and Areas allow you to register routes for each specific area.

If you've not used them before there is an MSDN walkthrough here:

http://msdn.microsoft.com/en-us/library/ee671793.aspx

Essentially, you have a directory for each area, which contains all your area-specific controllers and views, and in the route of that directory you place a file that registers the routes for that particular area like so:

public class MyAreaRegistration : AreaRegistration
 {
     public override string AreaName
     {
         get { return "My Area"; }
     }

     public override void RegisterArea(AreaRegistrationContext context)
     {
         context.MapRoute(
             "news-articles",
             "my-area/articles/after/{date}",
             new {controller = "MyAreaArticles", action = "After"}
             );

         // And so on ...
     }
}

In global.asax.cs you need to register all these extra areas, along with your other primary routes:

public static void RegisterRoutes(RouteCollection routes)
{
    AreaRegistration.RegisterAllAreas();

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

    routes.MapRoute(
        "Products",
        "products/show/{name}",
            new {controller = "Products", action = "Show", name = UrlParameter.Optional}
        );

    ...
}     


You can put a DefineRoutes(RouteCollection routes) method in each module, then call them all in Global.asax.cs.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜