一个简单的解决方案是简单地在默认(包罗万象)之上定义一个新路由,如下所示:
routes.MapRoute(
name: "ShortUrlToHomeActions",
url: "{action}",
defaults: new { controller = "Home" }
);
这种方法的问题是它会阻止访问Index
其他控制器的(默认操作)(请求/Other
, 当你有OtherContoller
with Index
操作将导致 404,请求/Other/Index
会工作)。
更好的解决方案是创建一个RouteConstraint
这将匹配我们的/{action}
仅在没有其他同名控制器的情况下:
public class NoConflictingControllerExists : IRouteConstraint
{
private static readonly Dictionary<string, bool> _cache = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
var path = httpContext.Request.Path;
if (path == "/" || String.IsNullOrEmpty(path))
return false;
if (_cache.ContainsKey(path))
return _cache[path];
IController ctrl;
try
{
var ctrlFactory = ControllerBuilder.Current.GetControllerFactory();
ctrl = ctrlFactory.CreateController(httpContext.Request.RequestContext, values["action"] as string);
}
catch
{
_cache.Add(path, true);
return true;
}
var res = ctrl == null;
_cache.Add(path, res);
return res;
}
}
然后应用约束:
routes.MapRoute(
name: "ShortUrlToHomeActions",
url: "{action}",
defaults: new { controller = "Home" },
constraints: new { noConflictingControllerExists = new NoConflictingControllerExists() }
);
See MSDN