2017-08-29 174 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