創建您自己的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();
編輯的替代解決方案
我發現子類路線則覆蓋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" }))
);
你可能是指'RemoveDashRouteHandler'。 – haim770
哦,快點。你是對的 – LostInComputer
是的..第二選擇似乎更好! –