这些asp.net mvc路由规则有什么问题?

时间:2010-09-03 20:47:31

标签: asp.net asp.net-mvc asp.net-mvc-2 routing

我在Global.asax.cs中定义了一系列路由:

   public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapRoute(null, "", // Only matches the empty URL (i.e. ~/)
                        new
                        {
                            controller = "Stream",
                            action = "Entry",
                            streamUrl = "Pages",
                            entryUrl = "HomePage"
                        }
        );

        routes.MapRoute(null, "{streamUrl}", // matches ~/Pages
                        new { controller = "Stream", action = "List" }
        );

        routes.MapRoute(null, "{streamUrl}/{entryUrl}", // matches ~/Pages/HomePage
                        new { controller = "Stream", action = "Entry" }
        );

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );

当我输入mydomain.com/或mydomain.com/Pages/HomePage时,路线完全符合我的预期。所以现在我正在写一个局部视图来生成一个链接列表。作为测试,我将此代码放在局部视图中:

<ul>
<% foreach (var item in Model) { %>

        <li id="<%:item.Text.Replace( " ", "-") %>">

            //This works - link shows up in browser as mydomain.com/
            <%: Html.RouteLink(item.Text, new{ streamUrl = "Pages", entryUrl = "HomePage" }) %>

            //This does not work - link shows up as mydomain.com/Blog?entryUrl=BlogEntryOne
            //instead of mydomain.com/Blog/BlogEntryOne
            <%: Html.RouteLink(item.Text, new{ streamUrl = "Blog", entryUrl = "BlogEntryOne" }) %>

        </li>

<% } %>
</ul>

我不确定为什么entryUrl路由值没有正确注册。我错过了什么?

1 个答案:

答案 0 :(得分:2)

非常习惯使用MVC,但我认为你应该先把更具体的路线放在第一位,如:

routes.MapRoute(null, "{streamUrl}/{entryUrl}", // matches ~/Pages/HomePage
                new { controller = "Stream", action = "Entry" }
);

routes.MapRoute(null, "{streamUrl}", // matches ~/Pages
                new { controller = "Stream", action = "List" }
);