【问题标题】:How to skip other action names while defining a custom route in mvc 4如何在 mvc 4 中定义自定义路由时跳过其他操作名称
【发布时间】:2013-09-17 14:30:27
【问题描述】:

我希望我的访问者能够通过输入该企业的名称重定向到该企业的详细信息页面。 所以我有这个自定义路线:

routes.MapRoute(
                "Business", 
                "{name}", 
                new { controller = "Business", action = "Show" },
                new[] { "Sample.Web.UI.Controllers" });

我默认有这个:

routes.MapRoute(
                "Default",
                "{controller}/{action}/{id}",
                new { controller = "Home", action = "Index", id = UrlParameter.Optional },
                new[] { "Sample.Web.UI.Controllers" });

在自定义之后排序。 最后,我有一个名为 show 的操作,它通过访问者输入的名称获取业务。 现在,当我在主页中拥有的每个 Index 操作方法如下:

@this.Html.ActionLink("More", "Index", "SomeThing")

重定向到 Sample/SomeThing 并调用我上面提到的动作 show 并返回 null。 无论如何我可以处理这个吗?

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-4 razor asp.net-mvc-routing routes


    【解决方案1】:

    我通过添加这个类解决了这个问题:

    public class NotEqual : IRouteConstraint
        {
            private readonly ICollection<string> match;
    
            public NotEqual(ICollection<string> match)
            {
                this.match = match;
            }
    
            public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
            {
                var result = new List<bool>();
                this.match.ToList()
                    .ForEach(m => 
                        result.Add(string.Compare(values[parameterName].ToString(), m, StringComparison.OrdinalIgnoreCase) != 0 &&
                        !values[parameterName].ToString().Contains("Test")));
                return result.TrueForAll(r => r);
            }
        }
    

    并像这样制作我的自定义路线:

    routes.MapRoute(
                    "Business",
                    "{name}",
                    new { controller = "Business", action = "Show" },
                    new { name = new NotEqual(new System.Collections.ObjectModel.Collection<string> { "Foo", "Test" }) },
                    new[] { "Sample.Web.UI.Controllers" });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-26
      • 2020-12-03
      • 1970-01-01
      • 2015-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多