使用可选参数路由

时间:2013-11-04 21:08:44

标签: asp.net-mvc url-routing

我有以下路由配置:

routes.MapRoute(
               name: "Pages",
               url: "{PageName}",
               defaults: new { controller = "Pages", action = "GetPageByName" }
            );

我需要对网站结构进行更改。我需要将以下网址路由到“pagesController”。两种情况下要发送到控制器的参数是'PageName':

http://domain.com/PageName/
http://domain.com/something/PageName

“某些东西”不是必需的,但可以添加,但不起作用。

可以这样做吗?

2 个答案:

答案 0 :(得分:0)

试试这个:

                routes.MapRoute(
                   name: "Pages",
                   url: "{something}/{PageName}",
                   defaults: new { controller = "Pages", action = "GetPageByName" }
                );

                routes.MapRoute(
                   name: "Pages",
                   url: "{PageName}",
                   defaults: new { controller = "Pages", action = "GetPageByName" }
                );

您必须按该顺序定义该路线将映射到GetPageByName

中的PagesController操作方法
public ActionResult GetPageByName(string pageName)
{

}

答案 1 :(得分:0)

刚设法做到了:

 routes.MapRoute(
               name: "Pages",
               url: "{stringURL}",
               defaults: new { controller = "Pages", action = "GetPageByStringURL" }
            );

            routes.MapRoute(
               name: "Pages2",
               url: "{x}/{stringURL}",
               defaults: new { controller = "Pages", action = "GetPageByStringURL" }
            );