How to make a custom route in ASP MVC
12,846
Noticed that attribute routing is also enabled.
routes.MapMvcAttributeRoutes();
you can also set up the route directly in the controller.
[RoutePrefix("ComicBooks")]
public class ComicBooksController : Controller {
[HttpGet]
[Route("{PermaLinkName}")] //Matches GET ComicBooks/Spiderman
public ActionResult ShowComicBook(string PermaLinkName){
//...get comic book based on name
return View(); //eventually include model with view
}
}
Author by
patrick
Updated on June 04, 2022Comments
-
patrick almost 2 years
I'm trying to do something like this.
MyUrl.com/ComicBooks/{NameOfAComicBook}
I messed around with RouteConfig.cs but I'm completely new at this, so I'm having trouble.
NameOfAComicBook
is a mandatory parameter.public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapMvcAttributeRoutes(); routes.MapRoute("ComicBookRoute", "{controller}/ComicBooks/{PermaLinkName}", new { controller = "Home", action = "ShowComicBook" } ); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } }
HomeController.cs
public ActionResult ShowComicBook(string PermaLinkName) { // i have a breakpoint here that I can't hit return View(); }