1

我不得不從網址等傳遞用戶請求:ASP .NET核心:路由。多個類別中的URL在begining

site.com/events/2017/06/wwdc.html 

或多個共同的:

site.com/category1/subcategory1/subcategory2/...../subcategoryN/page-title.html 

例如

site.com/cars/tesla/model-s/is-it-worth-it.html 

ArticlesController用行動Index(string title)或類似的東西。

在編譯時我不知道我會有多少段。但我知道,這些網址將以/{pageTitle}.html結尾。主要問題是,默認的asp.net核心路由不允許我寫東西,如{*}/pageTitle.html

這可能嗎?

回答

2

這是可能的,你幾乎做到了。

這條路線是

 app.UseMvc(routes => 
     { 
      routes.MapRoute(
       name: "all", 
       template: "{*query}", 
       defaults: new 
       { 
        controller = "Index", 
        action = "ArticlesController" 
       }); 
     }); 

編輯template: "{*query:regex(.+/.+\\.html$)}"將確保至少一個類別,並給出了冠軍的.html

而且在控制器的動作結束:

public IActionResult Index(string query) 
    { 
     string[] queryParts = query.Split(new char[] { '/' }); 
     string title = queryParts[queryParts.Length - 1]; 
     string[] categories = queryParts.Take(queryParts.Length - 1).ToArray(); 

     // add your logic about the title and the categories 

     return View(); 
    } 

請參閱documentation

專用傳統路由通常使用全部路由參數 (如{* article})來捕獲URL路徑的其餘部分。此 可能會使路由「太貪婪」,這意味着它與您想要與其他路由匹配的URL相匹配。在路由表中放入'貪婪的'路由 來解決這個問題。

+0

該航線將捕獲的所有請求,比如'類/ title.html'不僅事 唯一能幫助我的是把這個規則在最後... 感謝 – mokeev1995

+1

這條路線必須到位最後,對。 您可以通過在過濾器中應用正則表達式來過濾'category/title.html'等內容。 'template:「{* query:regex(。+ /。+ \\。html $)}」,'將完美滿足您的需求;)(如果運行良好,您也可以提出我的答案:-p) –

+0

不能,我沒有足夠的信譽... – mokeev1995