Asp.net mvc 5 ASP.NET MVC5路由-文章名称Url
我希望我的应用程序的行为如下所示: Url= ->控制器=物品 ->行动=索引 控制器中的索引方法如下所示:Asp.net mvc 5 ASP.NET MVC5路由-文章名称Url,asp.net-mvc-5,Asp.net Mvc 5,我希望我的应用程序的行为如下所示: Url= ->控制器=物品 ->行动=索引 控制器中的索引方法如下所示: public ActionResult Index(string title) { var article = GetArticle(title); return View(article); } 我以这种方式配置了我的路由: public static void RegisterRoutes(RouteCollectio
public ActionResult Index(string title)
{
var article = GetArticle(title);
return View(article);
}
我以这种方式配置了我的路由:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Article",
url: "{title}",
defaults: new { controller = "Article", action = "Index" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
问题是当我需要导航到ContactController的索引方法时:
它试图找到title==contact的文章
我知道我可以使用像mydomain/articles/{title}这样的路由,但我真的希望避免这种情况。我对路由约束不太了解,但我设法解决了这个问题 我将把我的博客标题改为contains-。我的超级文章 这是我的路线配置:
routes.MapRoute(
name: "Article",
url: "{title}",
defaults: new { controller = "Article", action = "Index" },
constraints: new { title = @"^.*-.*$" }
);
您可以编写自定义约束:
public class MyConstraint : IRouteConstraint
{
// suppose this is your blogPost list. In the real world a DB provider
private string[] _myblogsTitles = new[] { "Blog1", "Blog2", "Blog3" };
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
// return true if you found a match on your blogs list otherwise false
// in the real world you could query from DB to match blogs instead of searching from the array.
if(values.ContainsKey(parameterName))
{
return _myblogsTitles.Any(c => c == values[parameterName].ToString());
}
return false;
}
}
然后将此约束添加到路线中
routes.MapRoute(
name: "Article",
url: "{title}",
defaults: new { controller = "Article", action = "Index" }
constraints: new { title= new MyConstraint() }
);
看见