ASP.NET MVC5路由 - 文章名称URL

时间:2015-08-27 13:58:22

标签: asp.net-mvc-5

我希望我的应用行为如下:

网址= http://mydomain/one-of-my-blog-title      - >控制器=文章      - >行动=指数

控制器中的Index方法如下:

    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的索引方法时:

http://mydomain/contact

它试图找到title ==“contact”

的文章

我知道我可以使用像“mydomain / articles / {title}”这样的路线,但我真的想避免这种情况。

2 个答案:

答案 0 :(得分:0)

我对路线约束知之甚少,但我设法解决了这个问题。

我的博客标题将包含“ - ”。例子:我的超级文章

这是我的路线配置:

        routes.MapRoute(
          name: "Article",
          url: "{title}",
          defaults: new { controller = "Article", action = "Index" },
          constraints: new { title = @"^.*-.*$" } 
        );

答案 1 :(得分:0)

您可以编写自定义约束:

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() }
);