How to Route /About to /Home/About

2020-03-30 05:39发布

问题:

I am just getting started with ASP.NET MVC and it's great! However, I don't quite understand setting up routes.

How do I route ~/About to ~/Home/About?

/Views/Home/About.aspx

I would like to be able to access it with /Home/About or just /About

回答1:

If you want to explicity setup a route for it, you can do something like this:

routes.MapRoute( 
            "AboutRoute", 
            "About", 
            new { controller = "Home", action = "About" }  // Parameter defaults 
    );

I think thats what you want to do? I.e. have /About handled by the home controller?

The default route (as below) handles /Home/About

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


回答2:

In response to your comment on RM's answer - you don't actually need wildcards for that. Just do

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

Note, however, that you need to place this route at the very end of your route table (and you'll have to delete the default route), as this will catch every url that comes in.

You can use Phil Haack's Route Debugger to verify that your routes pick up urls as you expect.