【发布时间】:2017-07-26 03:26:01
【问题描述】:
我需要为其中一个网站提供以下功能。
http://www.example.com/[赞助商]/{controller}/{action}
根据[赞助商],必须定制网页。
我尝试将路由与 Application_Start 和 Session_Start 结合使用,但无法使其正常工作。
public static void RegisterRoutes(RouteCollection routes, string sponsor)
{
if (routes[sponsor] == null)
{
routes.MapRoute(
sponsor, // Route name
sponsor + "/{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
}
此外,没有 [sponsor] 的默认行为也应该起作用。 有人可以让我知道在 MVC3 URL 中有一个可选的第一个参数在技术上是否可行。如果是,请分享实现。谢谢。
更新代码 在按照 Sergey Kudriavtsev 的建议进行更改后,代码在给出值时工作。 如果未提供名称,则 MVC 不会路由到控制器/动作。
请注意,这仅适用于家庭控制器(包括非赞助商)。对于其他控制器/动作,即使指定了赞助商参数,它也不是路由。
请提出需要修改的地方。
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"SponsorRoute",
"{sponsor}/{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
"NonSponsorRoute",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional, sponsor = string.Empty }
);
}
动作方法
public ActionResult Index(string sponsor)
{
}
【问题讨论】:
标签: asp.net-mvc-3 asp.net-mvc-routing optional-parameters