2017-04-18 57 views
3

我正在尝试这样做。如何在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(); 
} 
+0

'NameOfAComicBook'是一个可选的参数吗?包含更多细节。 –

+0

@TetsuyaYamamoto我更新了我的问题。 (强制性的) – 0x4f3759df

+0

显示您的路线,包括您尝试的内容,并解释无法正常工作的内容。 –

回答

2

注意到属性的路由被允许。

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 
    } 
} 
+0

我的ComicBookRoute有Controller =”Home“,所以我期待它由HomeController处理。 – 0x4f3759df