我可以以某種方式獲得路由映射WebApiConfig中的控制器名稱嗎?Http Routing的控制器名稱?
我想要做的是將控制器名稱的一部分與操作進行匹配。
config.Routes.MapHttpRoute(
name: "ApiGetAllDefault",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional, action = "Get" + controllerName + "s" },
constraints: new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) }
);
更新:這樣做的原因是所有當我做路由作爲
config.Routes.MapHttpRoute(
name: "ApiById",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: new { id = @"^[0-9]+$" }
);
config.Routes.MapHttpRoute(
name: "ApiByActionId",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: null,
constraints: new { id = @"^[0-9]+$" }
);
config.Routes.MapHttpRoute(
name: "ApiByAction",
routeTemplate: "api/{controller}/{action}",
defaults: null
);
/* Default route */
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
與動作的名稱要求,是api/World/GetWorld/5
包括做比賽,但像api/World/5
一些其他請求沒有或分別會匹配多個動作。由於我沒有在路線和行動之間找到正確的默認映射,我有想法爲我的所有控制器定義更具體的路線。
foreach (Type t in GetTypesInNamespace(Assembly.GetExecutingAssembly(), "MyProject.Controllers")) {
if (typeof(ApiController).IsAssignableFrom(t)) { // Make sure that this controller class is deriving from api controller
string controllerName = t.Name.Substring(0, t.Name.LastIndexOf("Controller")); // Remove Controller postfix from name
config.Routes.MapHttpRoute(
name: "ApiGet" + controllerName,
routeTemplate: "api/" + controllerName + "/{id}",
defaults: new { controller = controllerName, action = "Get" + controllerName },
constraints: new { id = @"^[0-9]+$", httpMethod = new HttpMethodConstraint(HttpMethod.Get) }
);
config.Routes.MapHttpRoute(
name: "ApiGet" + controllerName + "s",
routeTemplate: "api/" + controllerName + "/{id}",
defaults: new { controller = controllerName, id = RouteParameter.Optional, action = "Get" + controllerName + "s" },
constraints: new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) }
);
}
}
該解決方案爲我工作,但我仍想知道是否有爲了匹配reuqest沒有動作名稱默認操作的通用途徑。
請解釋一點希望的結果。我不清楚你到底想要達到什麼目的。 – trailmax
@trailmax更新了說明。 – Explicat