我有ProgramController
,其中包含多种版本操作方法,例如EditDetails
,EditContacts
,EditRules
(另外还有10种,但为了简单起见,我会排除它们)。目前,此操作方法的URL类似于以下内容:
http://localhost/Program/1/EditContacts
http://localhost/Program/1/EditDetails
http://localhost/Program/1/EditRules
但我希望它们看起来如下:
http://localhost/Program/1/Contacts/Edit
http://localhost/Program/1/Details/Edit
http://localhost/Program/1/Rules/Edit
这对我来说更有意义。
到目前为止,这是我的RegisterRoutes
方法:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "ProgramInfo",
url: "Program/{id}/{action}",
defaults: new { controller = "Program"}
);
routes.MapRoute(
name: "ProgramDefault",
url: "Program/{action}",
defaults: new { controller = "Program", action = "Index" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
到目前为止,我找到的唯一方法是为每个操作方法设置一个路径,如下所示:
routes.MapRoute(
name: "EditContacts",
url: "Program/{id}/Contacts/Edit",
defaults: new { controller = "Program", action = "EditContacts" }
);
但我正在努力找到一个更好的解决方案来避免重复。我突然想到了以下内容,但不正确:
routes.MapRoute(
name: "EditProgram",
url: "Program/{id}/{variable}/Edit",
defaults: new { controller = "Program", action = "Edit" + "{variable}" }
);
提前感谢您的帮助。
答案 0 :(得分:0)
好像你想在联系人控制器中推送你的联系人,在详细信息控制器等中推送详细信息。它自然适合你描述网址空间的方式。
如果您想要另一个间接级别,可以使用区域。
注意:你可以根据RouteBase实现你自己的RouteHandler或你自己的路线,但对你的问题来说这似乎是一个非常大的锤子。
以下是此类方法的链接: http://www.dotnetcurry.com/showarticle.aspx?ID=970
答案 1 :(得分:0)
您需要将传入的路由值转换为现有的/ controller / action / id。
步骤1:创建自定义路由处理程序以转换路由
public class ReWriteUrlRouteHandler : IRouteHandler
{
private string _controllerName;
public ReWriteUrlRouteHandler(string controllerName)
{
_controllerName = controllerName;
}
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
var routeValues = requestContext.RouteData.Values;
var id = routeValues["id"];
var action = routeValues["action"];
var task = routeValues["task"];
var defaultAction = string.Format("{0}{1}", task, action);
//translate to default handler
requestContext.RouteData.Values["controller"] = _controllerName;
requestContext.RouteData.Values["action"] = defaultAction;
requestContext.RouteData.Values["id"] = id;
return new MvcHandler(requestContext);
}
}
步骤2:在路由表global.asax.cs中注册路由
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
var programRoute = new Route("Program/{id}/{action}/{task}", new ReWriteUrlRouteHandler("Program"));//your new route with controller name
routes.Add("ProgramRoute", programRoute);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
:)