【问题标题】:Routing where one of parameter values is part of URL path其中一个参数值是 URL 路径的一部分的路由
【发布时间】:2017-08-29 11:06:35
【问题描述】:

我对 Asp.Net core 1 中的路由感到困惑,我需要帮助。 在 startup.cs 我有这个配置

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

以及使用参数调用的函数。

但我想更改此网址并保持相同的功能。 我希望我的网址变成

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

所以,只有type 将是参数,并且entity 的名称将例如更改

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

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

但调用相同的函数。

这可能吗?

【问题讨论】:

    标签: c# asp.net-core routing


    【解决方案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"}
        );
    });
    

    【讨论】:

    • 路线顺序也很重要,因为第一场比赛获胜。默认路由也将匹配实体路由,因此您需要将实体路由放在默认路由之前,因为它更具体,不如默认路由通用
    • 好的,这就是我想要的。但在我的代码中我有这个 if 条件 if (entity == null) throw new Exception(String.Format("Entity with name {0} is unspecified", entity));现在怎么能现在实体的名字?
    • 我找到了 'template: "Entities/{entity}", ' ok ty dude
    猜你喜欢
    • 2023-04-08
    • 2013-06-08
    • 2011-11-25
    • 2020-05-15
    • 1970-01-01
    • 2021-12-28
    • 2011-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多