首页 > 解决方案 > 捕获所有以 GUID 结尾的 URL

问题描述

我正在 .Net Core 2.1 中构建一个 API,并有一个分页系统,用户可以在其中请求以可配置大小的块返回的大量卷。当一个块被发送时,它将包含一个 GUID,它是对下一个数据块的引用

例如,如果我们有一个返回 526 个结果的命中,它将数据分块为 5 x 100 和 1 x 26 记录块,第一个命中来自 GET /events/

第二页数据将来自类似 GET /events/95d9f018-bff9-46e7-ad86-9b9d6734cc0d

我的每个控制器方法上已经有许多路由

[HttpGet("/events/"]
public ActionResult GetAllEvents() {}

[HttpGet("/events/{EventId}"]
public ActionResult GetEvent(int EventId) {}

[HttpGet("/events/after/{AfterDate}"]
public ActionResult GetEventsAfter(DateTime AfterDate) {}

在某些情况下,方法可以有多个路由值。我想补充的是一个包罗万象的东西,如果 URL 以 GUID 结尾,它的路由方式会有所不同。

我现在看到的是,如果我附加一个 GUID,它会进入“GetEvent”方法

我尝试在 MVC 中添加路由

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "Continuation",
        template: "Route/{*ContinuationToken}",
        defaults: new { controller = "Continuation", action = "GetPagedResponse" },
        constraints: new { ContinuationToken = @"(?im)^[{(]?[0-9A-F]{8}[-]?(?:[0-9A-F]{4}[-]?){3}[0-9A-F]{12}[)}]?$" }
    );
});     

但显然这不是正确的实现方法,因为请求仍然路由到原始控制器和操作,而不是 ContinuationController

有没有办法将所有以 Guid 结尾的请求路由到特定的控制器和操作?

标签: model-view-controllerasp.net-core-mvcasp.net-mvc-routing

解决方案


尝试这样做,

在您希望传递继续令牌的控制器中添加此代码段,

        [Route("/continuation/{continuationToken:guid}")]
        public IActionResult nextResult(Guid continuationToken)
        {
            return View();
        }

在你的 Startup.cs 我有这个,类似于你的例子。

routes.MapRoute(
                    name: "guidroute",
                    template: "{controller}/{*guid:guid}",
                    defaults : new { controller = "continuation"}
                     );

并在默认路由之前添加。


推荐阅读