控制器上的多个路由
Multiple Routes on a Controller
想知道是否可以有多个路由指向一个 WebApi 控制器?
例如,我想让两个 http://domain/calculate and http://domain/v2/calculate 指向同一个控制器函数?
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "route1",
routeTemplate: "calculate",
defaults: new { controller = "Calculator", action = "Get" });
config.Routes.MapHttpRoute(
name: "route2",
routeTemplate: "v2/calculate",
defaults: new { controller = "Calculator", action = "Get" });
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
或
public class CalculatorController: ApiController
{
[Route("calculate")]
[Route("v2/calculate")]
public String Get() {
return "xxxx";
}
}
想知道是否可以有多个路由指向一个 WebApi 控制器?
例如,我想让两个 http://domain/calculate and http://domain/v2/calculate 指向同一个控制器函数?
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "route1",
routeTemplate: "calculate",
defaults: new { controller = "Calculator", action = "Get" });
config.Routes.MapHttpRoute(
name: "route2",
routeTemplate: "v2/calculate",
defaults: new { controller = "Calculator", action = "Get" });
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
或
public class CalculatorController: ApiController
{
[Route("calculate")]
[Route("v2/calculate")]
public String Get() {
return "xxxx";
}
}