Custom MVC Route - Separate Controller name in Url

2019-08-22 04:46发布

I have some controller class such as:

AdminProductController
AdminOrderController
AdminMessageController

and so on. Each controller class encapsulates admin-related tasks about particular subject. I want when user enter url like that:

Admin/Product/M1

the M1 action method of AdminProduct called.

of course one way is :

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

The problem with above code is for each controller class you must declare the above code. I want a general way to achieve this. Is there any solution?

1条回答
▲ chillily
2楼-- · 2019-08-22 05:20

You need to create a custom route.

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 }
        );
    }
}
查看更多
登录 后发表回答