0

I would like my app to behave like the following:

Url = http://mydomain/one-of-my-blog-title -> Controller = Article -> Action = Index

The Index method in the controller would like like this:

    public ActionResult Index(string title)
    {
        var article = GetArticle(title);
        return View(article);
    }

I configured my routes this way:

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

The problem is when I to navigate to the ContactController's index method:

http://mydomain/contact

It tries to find the article where title == "contact"

I know I could use a route like "mydomain/articles/{title}" but I would really like to avoid this..

Baral
  • 3,103
  • 2
  • 19
  • 28

2 Answers2

0

I did not know much about route constraint but I managed to figure this out.

I will have my blog title to contains "-". Exemple : my-super-article

This is my route config:

        routes.MapRoute(
          name: "Article",
          url: "{title}",
          defaults: new { controller = "Article", action = "Index" },
          constraints: new { title = @"^.*-.*$" } 
        );
Baral
  • 3,103
  • 2
  • 19
  • 28
0

You could write custom constraint:

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

and then add this constraint to your route.

routes.MapRoute(
    name: "Article",
    url: "{title}",
    defaults: new { controller = "Article", action = "Index" }
    constraints: new { title= new MyConstraint() }
);
Sam FarajpourGhamari
  • 14,601
  • 4
  • 52
  • 56