2

大师们,

在我的项目中,我指定了许多不同的路线,如下所示。

routes.MapRoute(
   name: "StudentMerit", 
   url: "Student-Merit", 
   defaults: new { controller = "StudentMerit", action = "GetData"});

routes.MapRoute(
   name: "StudentResults", 
   url: "Student-Results", 
   defaults: new { controller = "StudentResults", action = "GetData"});

如您所见,网址是连字符分隔的,我不太担心动作名称

如果我可以告诉 MVC 将连字符替换为 URL 中的任何内容,那么所有这些路由都可以重写,它将成为我的控制器。

就像是,

routes.MapRoute(
   name: "AllInOne", 
   url: "{Cont-roller}", 
   defaults: new { controller = {Cont-roller}.replace("-",""), action = "GetData"});

有没有办法做到这一点?请帮忙。

提前致谢。

4

1 回答 1

4

创建自己的 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" }))
);
于 2013-10-31T14:15:58.980 回答