2017-04-18 55 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