简体   繁体   中英

Advanced MVC.NET Routing

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM