0

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

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 的操作,它通过访问者输入的名称获取业务。现在,当我在主页中拥有的每个索引操作方法都像:

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

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

4

1 回答 1

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" });
于 2013-09-19T10:43:10.710 回答