0

我有一些控制器类,例如:

AdminProductController
AdminOrderController
AdminMessageController

等等。每个控制器类都封装了有关特定主题的管理相关任务。我想当用户输入这样的网址时:

Admin/Product/M1

被调用的M1动作方法。AdminProduct

当然一种方法是:

routes.MapRoute("AdminProduct", "Admin/Product/{action}", new { controller = "AdminProduct", action = "Index" });

上面代码的问题是对于每个控制器类,您必须声明上面的代码。我想要一个通用的方法来实现这一点。有什么解决办法吗?

4

1 回答 1

0

您需要创建自定义路由。

public class AdminRoute : Route
{
 public AdminRoute(string url, IRouteHandler routeHandler) 
     : base(url, routeHandler) {}
 public AdminRoute(string url, RouteValueDictionary defaults, 
     IRouteHandler routeHandler) : base(url, defaults, routeHandler) {}
 public AdminRoute(string url, RouteValueDictionary defaults, 
     RouteValueDictionary constraints, IRouteHandler routeHandler) 
     : base(url, defaults, constraints, routeHandler){}
 public AdminRoute(string url, RouteValueDictionary defaults, 
     RouteValueDictionary constraints, RouteValueDictionary dataTokens, 
     IRouteHandler routeHandler) 
     : base(url, defaults, constraints, dataTokens, routeHandler){}

    public override RouteData GetRouteData(HttpContextBase httpContext)
    {
        RouteData data = base.GetRouteData(httpContext);

        if (data != null)
            data.Values["controller"] = "Admin" + data.Values["controller"];

        return data;
    }
}
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.Add(new AdminRoute("Admin/{controller}/{action}/{id}", 
            new RouteValueDictionary(
                new { controller = "Home", action="Index", 
                id = UrlParameter.Optional }), new MvcRouteHandler()));

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { 
                controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}
于 2013-05-12T19:56:01.077 回答