I am currently trying to route in the following way.
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.