2017-08-29 136 views
0

我很困惑與Asp .Net核心1路由,我需要幫助。 在startup.cs我有這個配置Asp網絡核心與路由混淆

 app.UseMvc(routes => 
     { 
      routes.MapRoute(
       name: "default", 
       template: "{controller=Home}/{action=Index}/{id?}");  
     }); 

我創建了一個控制器「實體」和方法「獲取」

[Authorize] 
public class EntitiesController : Controller 
{      
    [Produces("text/html")] 
    public string Get(string entity, string type) 
    {    
     return "<html><body>test</body></html>"; 
    } 

} 

所以,當我在URL鏈接文本類似下面的工作

http://localhost:12895/Entities/Get?entity=entity&type=type

和用params調用的函數。

但我想更改此網址並保持相同的功能。 我想我的網址成爲 http://localhost:12895/Entities/entity?type=type

所以,只有「類型」將參數與「實體」的名稱將例如 http://localhost:12895/Entities/human?type=type

http://localhost:12895/Entities/dog?type=type

改變,但調用相同的功能。

這可能嗎?

回答

1

There's有關.net核心路由的完整信息。

是的。有可能的。爲您的班級添加額外的路線app.UseMvc

它應該看起來像路線的

app.UseMvc(routes => 
{ 
    routes.MapRoute(
     name: "default", 
     template: "{controller=Home}/{action=Index}/{id?}" 
    );  


    routes.MapRoute(
     name: "entities", 
     template: "Entities/{entity}", 
     defaults: new { controller = "Entities", action = "Get"} 
    ); 
}); 
+1

訂單也如第一場比賽的勝利非常重要的。默認路由也會匹配實體路由,因此您需要將實體路由放置在默認路由之前,因爲它更具體,並且不像默認路由一般。 – Nkosi

+0

好的作品就是我想要的。但在我的代碼中,如果條件if(實體== null) 拋出新的異常(String.Format(「名稱爲{0的實體未指定」,entity));現在怎麼可以現在的實體名稱? – GomuGomuNoRocket

+0

我發現'template:「Entities/{entity}」,'ok ty dude – GomuGomuNoRocket