【问题标题】:Partially match route in WebAPI ControllerWebAPI 控制器中的部分匹配路由
【发布时间】:2014-08-06 17:40:18
【问题描述】:

有没有办法使用 WebAPI 仅匹配 URL 的第一部分(特别是属性路由)。类似于匹配多个预先不知道数字的可选路径组件的方法。

例如:[Route("v{ver}/search/{remainingPath})] 匹配路径 v1/search/productsv2/search/customers/1234

我想利用 WebAPI 强大的路由匹配框架,但 search 之后的路径组件不会成为控制器/动作匹配过程的一部分。

【问题讨论】:

    标签: c# asp.net-web-api asp.net-web-api-routing attributerouting


    【解决方案1】:

    您应该能够覆盖路由处理程序以拦截请求并进行自定义路由。我从来没有做过,但看起来你可以实现 HttpControllerDispatcher 并覆盖 SendAsync 方法来更改请求。

    public class CustomRouteHandler : HttpControllerDispatcher
    {
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            //Your code here to change the route
    
            return base.SendAsync(request, cancellationToken);
        }
    }
    

    查看海报,了解您可以在 Web api 管道中覆盖的内容。 http://www.asp.net/posters/web-api/asp.net-web-api-poster.pdf

    这里还有一些关于路由的文章可能会有所帮助。 http://www.asp.net/web-api/overview/web-api-routing-and-actions

    【讨论】:

      【解决方案2】:

      将您的路线模板更改为[Route("v{ver}/search/{*remainingPath})]?...这里* 将允许search 段之后的任意数量的段与您的路线相匹配...

      【讨论】:

      • 获得匹配需要什么参数类型?我试过stringstring[]IEnumerable&lt;string&gt;List&lt;string&gt;object,结果总是为空。如果我添加多个路径段,我也会得到 404。您是否有指向此功能文档的链接? Google 很难找到“*”,但我可能会遗漏一些东西。
      • 将操作上的参数命名为remainingPathstring 类型),该参数现在应该包含其余路径段...
      • 它对我不起作用:see here。我可以访问http://localhost:33378/v1/search/test/other/,但当我尝试添加更多路径段(http://localhost:33378/v1/search/test/other/path/)时,remainingPath 仍然为空且 IIS 404。 NuGet 说我正在使用 AttributeRouting.WebApi 3.5.6。此外,如果我尝试将 remainingPath 设为非可选参数,它无法找到控制器的操作(至少它使控制器正确)。
      • 我的错误格式应该是{*remainingPath}而不是{remainingPath*}...注意*的位置..
      • 太棒了!尾随的* 看起来类似于正则表达式零或多个运算符,它适合这种情况,所以我什至没有想过尝试其他方式。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多