Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a custom route in ASP MVC

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();
}
like image 761
patrick Avatar asked Apr 18 '17 00:04

patrick


People also ask

What is custom route in MVC?

A custom route constraint can also be used with a Convention based routing. The new version MVC has an override version MapRoute method that accepts a constraint as a parameter. Using this method we can pass over a custom constraint.

How can add route in ASP.NET MVC?

routes. MapRoute( name: "RootLogin", url: "amer/us/en/login/index/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter. Optional } ); routes. MapRoute( name: "DefaultAmer", url: "amer/us/en/{controller}/{action}{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.

What is custom routing?

Custom routing allows you to display SEO-friendly URLs on your site that map behind-the-scenes to conventional Kibo eCommerce resources such as a product page or a search results page.

Where you configure route in MVC?

Configure a Route Every MVC application must configure (register) at least one route configured by the MVC framework by default. You can register a route in RouteConfig class, which is in RouteConfig. cs under App_Start folder.


1 Answers

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
    }
}
like image 76
Nkosi Avatar answered Sep 29 '22 21:09

Nkosi