我在Web API服务中构建动态路由系统。
例如,服务可能有多条路线(我不知道应用程序启动时的确切计数和前缀)。我想创建一些自定义路由来决定选择哪条路由(某种内部重定向到另一条路由),在第一个请求上初始化它并将请求传递给它。
我尝试从HttpRoute继承并覆盖GetRouteData,但由于某种原因,在IHttpRouteData服务器中更改路由后,返回406 Not Notcecece状态代码。只有一条替代路线的简单例子:
public static void Register(HttpConfiguration config) // on Application_Start
{
WebApiConfig.Configuration.Routes.Add("InitRoute", new LazyInitializationRoute("myservice/{*params}"));
}
public class LazyInitializationRoute : HttpRoute
{
private static bool _initialized = false;
public LazyInitializationRoute(string routeTemplate)
: base(routeTemplate) { }
public override IHttpRouteData GetRouteData(string virtualPathRoot, HttpRequestMessage request)
{
IHttpRouteData baseRouteData = base.GetRouteData(virtualPathRoot, request);
if (baseRouteData == null) return null;
if (!_initialized)
{
WebApiConfig.Configuration.Routes.MapHttpRoute("MyRoute", "myservice");
_initialized = true;
}
IHttpRoute odataRoute = WebApiConfig.Configuration.Routes["MyRoute"];
var values = baseRouteData.Values;
IHttpRouteData routeData = values == null ? new HttpRouteData(odataRoute) : new HttpRouteData(odataRoute, new HttpRouteValueDictionary(values));
return routeData;
}
}
请帮忙。我怎样才能实现理想的行为?