在Web API Controller中部分匹配路由

时间:2014-06-16 20:14:01

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

有没有办法只使用WebAPI匹配URL的第一部分(具体是属性路由)。类似于匹配多个可选路径组件的方法,其中数字事先是未知的。

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

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

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:0)

您应该能够覆盖路由处理程序以拦截请求并执行自定义路由。我从来没有这样做过,但看起来你可以实现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