我有一些控制器类,例如:
AdminProductController
AdminOrderController
AdminMessageController
等等。每个控制器类都封装了与特定主题相关的管理相关任务。 我希望当用户输入这样的URL时:
Admin/Product/M1
调用M1
的{{1}}操作方法。
当然有一种方法是:
AdminProduct
上面代码的问题是每个控制器类必须声明上面的代码。 我想要一个通用的方法来实现这一目标。有没有解决方案?
答案 0 :(得分: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 }
);
}
}