【问题标题】:What's wrong with these asp.net mvc routing rules?这些 asp.net mvc 路由规则有什么问题?
【发布时间】:2010-09-03 20:47:31
【问题描述】:

我在 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 路由值。我错过了什么?

【问题讨论】:

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


    【解决方案1】:

    我不太非常习惯于 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" }
    );
    

    【讨论】:

    • 哦天哪...我无法透过树木看到森林。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2013-02-15
    • 1970-01-01
    • 2018-07-13
    • 1970-01-01
    • 2013-11-13
    • 2011-11-30
    • 2013-06-07
    相关资源
    最近更新 更多