1

我有一个名为的控制器Entry,它具有三个 ActionResult:ViewNewEdit

View操作接受表示特定条目对象的字符串参数。

我试图弄清楚如何不在 URL 中显示“查看”一词。换句话说,我希望它像默认操作一样。

理想情况下,我希望 URL 读取为:

  • 给定条目的 /entry/2DxyJR
  • /entry/new创建一个新条目
  • /entry/edit/2DxyJR编辑给定条目

我相信这可以通过自定义路线来完成,但我不确定如何实际做到这一点。这条路线适用于隐藏“视图”,但是/new不起作用/edit

routes.MapRoute(
    name: "Entry",
    url: "entry/{id}",
    defaults: new { controller = "Entry", action = "View", id = UrlParameter.Optional }
);

抱歉,这非常愚蠢,但我仍在努力了解路由的工作原理。

4

2 回答 2

2

您需要确保将更具体的放在顶部,因此条目/id 必须放在最后,因为您似乎有基于字符串的 id。

这将首先匹配最明确的(新),然后如果 url 中有编辑,则如果没有则进入查看操作。

routes.MapRoute(
    name: "Entry",
    url: "entry/new",
    defaults: new { controller = "Entry", action = "New" }
);

routes.MapRoute(
    name: "Entry",
    url: "entry/edit/{id}",
    defaults: new { controller = "Entry", action = "Edit", id = UrlParameter.Optional }
);

routes.MapRoute(
    name: "Entry",
    url: "entry/{id}",
    defaults: new { controller = "Entry", action = "View", id = UrlParameter.Optional }
);
于 2012-09-07T20:24:41.597 回答
1

我认为路由约束实现在“entry/”后面传递所有字符串,但除了 view、edit 和 new 之类的词,因此“默认”路由可以处理。就像是:

public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");


            routes.MapRoute(
                "EntryView",
                "Entry/{identifier}",
                new { controller = "Entry", action = "View" },
                new { identifier = new NotEqual(new string[]{"View", "Edit" , "New"}) }

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

这是 NotEqual 类:

public class NotEqual : IRouteConstraint
    {
        private string[] _match;

        public NotEqual(string[] match)
        {
            _match = match;
        }

        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            for (int i = 0; i < _match.Length; i++)
            {
                if (String.Compare(values[parameterName].ToString(), _match[i], true) == 0)
                {
                    return false;
                }
            }
            return true;
        }
    }

我对其进行了测试并且它有效,我在http://stephenwalther.com/archive/2008/08/07/asp-net-mvc-tip-30-create-custom-route-constraints.aspx上找到了它,因为我需要它

于 2012-09-07T21:58:18.257 回答