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

ast*_*ght 5 c# asp.net-mvc asp.net-mvc-routing

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

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

    }
}
Run Code Online (Sandbox Code Playgroud)

HomeController.cs

public ActionResult ShowComicBook(string PermaLinkName)
{


    // i have a breakpoint here that I can't hit


    return View();
}
Run Code Online (Sandbox Code Playgroud)

Nko*_*osi 5

请注意,属性路由也已启用。

routes.MapMvcAttributeRoutes();
Run Code Online (Sandbox Code Playgroud)

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

[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
    }
}
Run Code Online (Sandbox Code Playgroud)