如何在 ASP MVC 中创建自定义路由

How to make a custom route in ASP MVC

我正在尝试做这样的事情。

MyUrl.com/ComicBooks/{NameOfAComicBook}

我搞砸了 RouteConfig.cs 但我对此完全陌生,所以我遇到了麻烦。 NameOfAComicBook 是必填参数。

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();
}

注意到属性路由也已启用。

routes.MapMvcAttributeRoutes();

也可以直接在控制器中设置路由

[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
    }
}