发生这种情况是因为默认路由(假设您有一个)仍将匹配 Elmah.Mvc.ElmahController。
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional });
无论您是否愿意,路由的“{controller}”部分都会找到匹配的控制器。在这种情况下,这显然是有问题的。
您可以使用 IRouteConstraint 为您的路线添加约束,概述 here。 NotEqual 约束实际上非常有用。
using System;
using System.Web;
using System.Web.Routing;
public class NotEqual : IRouteConstraint
{
private string _match = String.Empty;
public NotEqual(string match)
{
_match = match;
}
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
return String.Compare(values[parameterName].ToString(), _match, true) != 0;
}
}
然后使用以下命令将 ElmahController 从默认路由中排除。
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new { controller = new NotEqual("Elmah") });
这将使对“/elmah”的请求返回 404。