我发现 ASP.NET Web Api 中的路由基类存在细微差别,这迫使我编写了一个小助手类,它允许我只定义一次路由。是否有一个原因?我假设对框架的更改太大,无法使两者RouteCollection
都从同一个基类派生或实现相同的接口(这会使这个类变得更简单)
public static class RouteMapper
{
private class Route
{
public string Name { get; set; }
public string Template { get; set; }
public object Defaults { get; set; }
public Route(string name, string template, object defaults)
{
Name = name;
Template = template;
Defaults = defaults;
}
}
private static List<Route> GetRoutes()
{
return new List<Route>
{
new Route(
"API Default",
"api/{controller}/{id}",
new {id = RouteParameter.Optional})
};
}
public static void AddHttpRoutes(this HttpRouteCollection routeCollection)
{
var routes = GetRoutes();
routes.ForEach(route => routeCollection.MapHttpRoute(route.Name, route.Template, route.Defaults));
}
public static void AddHttpRoutes(this RouteCollection routeCollection)
{
var routes = GetRoutes();
routes.ForEach(route => routeCollection.MapHttpRoute(route.Name, route.Template, route.Defaults));
}
}
这允许我AddHttpRoutes
在我的 Global.asax 和我的集成测试中调用一个简单的方法。
集成测试
var configuration = new HttpSelfHostConfiguration("http://localhost:20000");
configuration.Routes.AddHttpRoutes();
_server = new HttpSelfHostServer(configuration);
_server.OpenAsync().Wait();
全球.asax
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.AddHttpRoutes();
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
这是一个已知问题吗?它可能会在以后的 ASP.NET Web Api 版本中得到修复吗?