更新
您可能还想研究基于属性的路由,这可能是一个更简洁的解决方案,只有您使用路由属性注释的操作才会与路由匹配,这可能会帮助您实现您想要的。
或者
尽管可能有比这更好的方法,但如果您实现自定义,IRouteConstraint
例如this article ,它是可能的。
您可以改进的高度粗略和现成的方法如下:
public class IfActionExistsConstraint : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
var actionName = values["Action"] as string;
if (actionName == null)
{
return false;
}
var controllerName = values["Controller"] as string;
var controllerTypeResolver = GlobalConfiguration.Configuration.Services.GetHttpControllerTypeResolver();
var controllerTypes = controllerTypeResolver.GetControllerTypes(GlobalConfiguration.Configuration.Services.GetAssembliesResolver());
var controllerType = controllerTypes.SingleOrDefault(ct => ct.Name == string.Format("{0}Controller", controllerName));
if(controllerType == null)
{
return false;
}
return controllerType.GetMethod(actionName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance) != null;
}
}
登记:
var apiroute = routes.MapHttpRoute(
name: "API Default",
routeTemplate: "api/{language}-{country}/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: new { IfActionExistsConstraint = new IfActionExistsConstraint() }
);