问题
This is ok:
GlobalConfiguration.Configuration.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}",
defaults: new { id = System.Web.Http.RouteParameter.Optional });
But I want to redirect incoming requests to ApiFolder folder's class
回答1:
You should specify your namespace in your route configuration:
var r = GlobalConfiguration.Configuration.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}",
defaults: new { id = System.Web.Http.RouteParameter.Optional },
);
if( r.DataTokens == null ){
r.DataTokens = new RouteValueDictionary();
}
r.DataTokens["Namespaces"] = new string[] {"ApiFolder"};
回答2:
Kenneth's suggestion wont work as stated in the comments.
However you can write your own implementation of IHttpControllerSelector and only assign it when you map the api routes. I used the implementation in this article as a base and modified it.
Then its just the small issue of replacing the default selector after mapping the route in WebApiConfig like this (where CustomControllerSelector is my implementation):
public static void Register(HttpConfiguration configuration)
{
var apiRoute = configuration.Routes.MapHttpRoute(
name: "API Default",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional, controllerNamespace = "api" }
);
configuration.Services.Replace(typeof(IHttpControllerSelector), new CustomControllerSelector(configuration));
}
来源:https://stackoverflow.com/questions/16609561/redirecting-route-in-asp-net-webapi