I would like to create a dynamic routing to a URL like following:
http://localhost:51577/Item/AnyActionName/Id
Please note that the controller name is static and doesn't need to be dynamic. On the other hand, I need to have the action name part dynamic so that whatever is written in that part of URL, I would redirect the user to the Index
action inside of Item
controller.
What I have tried so far is:
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
"Items",
"Item/{action}/{id}",
new { controller = "Item", action = "Index", id = UrlParameter.Optional });
}
And when I build my app I get a following error:
The resource cannot be found.
Edit:
Here is my Global.asax
file and the routeconfig.cs
file:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
And here's the content of the RouteConfig.cs
file with the answer that @Nkosi provided:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Items",
url: "Item/{id}/{*slug}",
defaults: new { controller = "Item", action = "Index", slug = UrlParameter.Optional }
);
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…