0
votes

I am currently trying to route in the following way.

  • / routes to Home controller, view action, "home" as id
  • /somePageId routes to Home controller, view action, "somePageId" as id
  • /Videos routes to Videos controller, index action
  • /Videos/someVideoName routes to Videos controller, video action with id param as "someVideoName"
  • /News routes to News controller, index action
  • /News/someNewsId routes to news controller, view action, "someNewsId" as the id.

So far, i have the following code:

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

routes.MapRoute(
    name: "NewsIndex",
    url: "News",
    defaults: new { controller = "News", action = "Index" },
    namespaces: new[] { "TheSportsOfficeWeb.Controllers" }
);

routes.MapRoute(
    name: "NewsView",
    url: "News/{id}",
    defaults: new { controller = "News", action = "_", id = UrlParameter.Optional },
    namespaces: new[] { "TheSportsOfficeWeb.Controllers" }
);

routes.MapRoute(
    name: "PageShortCut",
    url: "{id}",
    defaults: new { controller = "Home", action = "_", id = UrlParameter.Optional },
    namespaces: new[] { "TheSportsOfficeWeb.Controllers" }
);

If i go to /Home/_/About, i can view the page, if i go to /About, i just get a 404.

Is this possible in mvc.net? If so, how would i go about this?

1
Side note: order of routes in your sample is backward - default route would match everything and more specific routes will never get tested. Make sure to fix sample to show reasonable (most specific- to-least specific) order of routes before any suggestions can be made. - Alexei Levenkov

1 Answers

2
votes

Try removing UrlParameter.Optional from the PageShortCut route. You'll also probably have to reorder the routes.

This works for me (as the final two routes):

routes.MapRoute(
    name: "PageShortCut",
    url: "{id}",
    defaults: new { controller = "Home", action = "_" },
    namespaces: new[] { "TheSportsOfficeWeb.Controllers" }
);

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

And my controller:

public class HomeController : Controller {
    public string Index(string id) {
        return "Index " + id;
    }

    public string _(string id) {
        return id;
    }
}

When you tell the routing engine that id is not optional for a route, it won't use the route unless id is present. That means that the engine will fall to the Default route for URLs without any parameters.