mvc how to change default route

2020-04-01 03:12发布

I'm going through the Pro Asp.net mvc3 framework book. I wanting to change the default route so that I can have a different home page. I've added a new controller called Pages and a view called Home. This is what I'm wanting as my home page.

I've tried adding this to my global.asax.cs

routes.MapRoute("MyRoute", "{controller}/{action}/{id}",
                new { controller = "Pages", action = "Home", id = "DefautId" });

This changes the default page, but it screws up the categories

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


        routes.MapRoute(null,
                        "", // Only matches the empty URL (i.e. /)
                        new
                            {
                                controller = "Product",
                                action = "List",
                                category = (string) null,
                                page = 1
                            }
            );

        routes.MapRoute(null,
                        "Page{page}", // Matches /Page2, /Page123, but not /PageXYZ
                        new {controller = "Product", action = "List", category = (string) null},
                        new {page = @"\d+"} // Constraints: page must be numerical
            );

        routes.MapRoute(null,
                        "{category}", // Matches /Football or /AnythingWithNoSlash
                        new {controller = "Product", action = "List", page = 1}
            );

        routes.MapRoute(null,
                        "{category}/Page{page}", // Matches /Football/Page567
                        new {controller = "Product", action = "List"}, // Defaults
                        new {page = @"\d+"} // Constraints: page must be numerical
            );

        routes.MapRoute(null, "{controller}/{action}");
    }

What should I do to make this work?

UPDATE:

URLS: Home page goes to List of items

http://localhost/SportsStore/ 

clicked category

http://localhost/SportsStore/Chess?contoller=Product 

Controller that is hit for the home page

 public class ProductController : Controller
    {
        private readonly IProductRepository repository;
        public int PageSize = 4;

        public ProductController(IProductRepository repoParam)
        {
            repository = repoParam;
        }


        public ViewResult List(string category, int page = 1)
        {
            var viewModel = new ProductsListViewModel
                                {
                                    Products = repository.Products
                                        .Where(p => category == null || p.Category == category)
                                        .OrderBy(p => p.ProductID)
                                        .Skip((page - 1)*PageSize)
                                        .Take(PageSize),
                                    PagingInfo = new PagingInfo
                                                     {
                                                         CurrentPage = page,
                                                         ItemsPerPage = PageSize,
                                                         TotalItems = category == null
                                                                          ? repository.Products.Count()
                                                                          : repository.Products.Where(
                                                                              e => e.Category == category).Count()
                                                     },
                                    CurrentCategory = category
                                };

            return View(viewModel);
        }

Controller that I'm wanting to be hit for the home page

public class PagesController : Controller
{
    public ViewResult Home()
    {
        return View();
    }

}

thanks,

3条回答
贼婆χ
2楼-- · 2020-04-01 03:55

I was able to get it to work like this:

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

    routes.MapRoute(null, "", new {controller = "Pages", action = "Home"});

    //routes.MapRoute(null,
    //                "", // Only matches the empty URL (i.e. /)
    //                new
    //                    {
    //                        controller = "Product",
    //                        action = "List",
    //                        category = (string)null,
    //                        page = 1
    //                    }
    //    );

    routes.MapRoute(null,
                    "Page{page}", // Matches /Page2, /Page123, but not /PageXYZ
                    new {controller = "Product", action = "List", category = (string) null},
                    new {page = @"\d+"} // Constraints: page must be numerical
        );

    routes.MapRoute(null,
                    "{category}", // Matches /Football or /AnythingWithNoSlash
                    new {controller = "Product", action = "List", page = 1}
        );

    routes.MapRoute(null,
                    "{category}/Page{page}", // Matches /Football/Page567
                    new {controller = "Product", action = "List"}, // Defaults
                    new {page = @"\d+"} // Constraints: page must be numerical
        );


    //routes.MapRoute(null, "{controller}/{action}");

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

    //routes.MapRoute("MyRoute", "{controller}/{action}",
    //    new { controller = "Pages", action = "Home" });

is there a better way?

查看更多
聊天终结者
3楼-- · 2020-04-01 03:57

Be sure to place the default route at the very end of the route mappings. If it's last there's no way it can screw up the categories route.

Update If this route:

routes.MapRoute(null, "{controller}/{action}");

comes before the default, it will catch anything that you would expect your default route to catch except items with a third URL parameter (id).

So for example:

/somepage/home

would get caught by this above route, rather than your default.

So you probably want to delete this route.

查看更多
ら.Afraid
4楼-- · 2020-04-01 04:00

First option is to use this way of page routing:

routes.MapRoute("Give route a name btw","Page/{page}", // Matches /Page/2
   new {controller = "Product", action = "List", category = urlParameter.Optional},
   new {page = @"\d+"} 
);

This way your routes will be more REST way.

Other way - use regex routes Defining routes using regular expressions

PS: Cant check if this link is online now. Was ok couple of days ago.
PS2: And Faust is right about route order. Greedy routes go last.
PS3: Can you write URL scheme you want to implement?

查看更多
登录 后发表回答