创建自己的 RouteHandler。我不知道这是否是最好的解决方案。
public class RemoveDashRouteHandler : MvcRouteHandler
{
protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
{
requestContext.RouteData.Values["controller"] = ((string)requestContext.RouteData.Values["controller"]).Replace("-", String.Empty);
return base.GetHttpHandler(requestContext);
}
}
用法
routes.MapRoute(
name: "AllInOne",
url: "{controller}",
defaults: new { controller = "Default", action = "GetData" }
).RouteHandler = new RemoveDashRouteHandler();
编辑替代解决方案
我通过子类化Route然后覆盖GetRouteData找到了一个更好的解决方案(在我看来)。更好的是,Route 的职责是生成 RouteData,而 MvcRouteHandler 的职责是获取 IHttpHandler。
public class RemoveDashRoute : Route
{
private const string ControllerKey = "controller";
public RemoveDashRoute(string url, RouteValueDictionary defaults, RouteValueDictionary constraints = null, RouteValueDictionary dataTokens = null, IRouteHandler routeHandler = null)
: base(url, defaults, constraints ?? new RouteValueDictionary(), dataTokens ?? new RouteValueDictionary(), routeHandler ?? new MvcRouteHandler())
{
}
public override RouteData GetRouteData(HttpContextBase httpContext)
{
var routeData = base.GetRouteData(httpContext);
if (routeData != null && routeData.Values.ContainsKey(ControllerKey))
{
routeData.Values[ControllerKey] = ((string)routeData.Values[ControllerKey]).Replace("-", String.Empty);
}
return routeData;
}
}
用法
routes.Add("AllInOne", new RemoveDashRoute(
url: "{controller}",
defaults: new RouteValueDictionary(new { controller = "Home", action = "GetData" }))
);