如何在ASP.NET Core MVC中创建数字路由

时间:2018-05-24 15:31:26

标签: asp.net-core routing asp.net-core-mvc

我想要一个像这样的URL路径模式:

http://example.com/15/232

第一段和第二段均由整数值组成。如果不满足此模式,我希望路由回退到默认的{controller=Home}/{action=Index}模式。

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:2)

我可能会做的是修改您的startup.cs以反映您的新路线:

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "segment",
        template: "{segment1:int}/{segment2:int}", //<-- Matches /15/232
        defaults: new { controller = "Home", action = "Segment" }
    );

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

新路由只指向一个控制器和操作,然后根据路径返回相应的内容视图。

public IActionResult Segment(int segment1, int segment2)
{

    return View()
}