Another MVC routing problem

2019-08-10 04:42发布

问题:

One day I'll understand routing but this is what I have:

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



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

        }

If I go to http://localhost all is ok

If I go to http://localhost/Home/Index/1234 all is ok

if I go to http://localhost/1234 it 404's

I tried Phil Haack's route debugger but because it throws a 404 the route debugger doesnt work.

What do I have to do In RegisterRoutes for http://localhost/1234 to work

回答1:

routes.MapRoute(
    "LicenceCode",
    "{LicenceCode}"
    new { controller = "Home", action = "Index", LicenceCode = UrlParameter.Optional } // Parameter defaults
);

Then /1234 will route to the Index action of Home controller:

public ActionResult Index(string licenceCode)
{
    ...
}


回答2:

You have to use following root instead of yours:

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


回答3:

I don't have Visual Studio in front of me, but I think it would be

routes.MapRoute(
    "Default2",
    "{LicenceCode}",
    new { controller = "Home", action = "Index", LicenceCode = UrlParameter.Optional }
);

You'll definitely want to put this last in your route registrations as this would hijack quite a few paths, I would imagine.



回答4:

Setup a default route as mentioned above routes.MapRoute( "Default", // Route name "{LicenceCode}", // URL with parameters new { controller = "Home", action = "Index", LicenceCode = UrlParameter.Optional } // Parameter defaults );

but then DO NOT ADD 1,000 lines of routes in the global.asax I have seen this done on a few MVC 1 sites and it is really awful to maintain.

For other routes, handle them through Views and controllers. Example:

  1. In a Controller: in a ActionResults method, you can do return RedirectToAction("ClientEnrollment", "Cis");

  2. In a view : Having a link @Html.ActionLink("Select", "ClientDetails", "Cis", new { id = item.ClientId }, null) |