How to handle this routing?

I have a url:

  • / nl / blog (shows an overview of blog items)
  • / nl / blog / loont-lekker-koken-en-wordt-eerlijkheid-beloond (shows a blog element with urltitle)
  • / nl / blog / waarom-liever-diΓ«tist-dan-kok (shows a blog element with urltitle)

for which I defined the routes:

  • A: route "nl / blog / {articlepage}" with the restriction articlepage = @ "\ d"
  • B: nl / blog route
  • C: route "nl / blog / {urltitle} / {commentpage}" with commentpage = = "" \ d "
  • D: route "nl / blog / {urltitle}"

Question 1: this works great, but maybe there is a better solution with fewer routes?

Question 2: to add a new article, I have an AddArticle action method in BlogController. Of course, with the above routes, the URL "/ nl / blog / addarticle" will map to route D, where addarticle will be a URL that, of course, does not comply with the rule. So I added the following route:

  • E: route "nl / blog / _ {action}"

and therefore, now the URL "/ nl / blog / _addarticle" maps to this route and performs the correct action method. But I was wondering if there is a better way to handle this?

Thanks for the advice.

+6
source share
1 answer

Answers to my questions:

For the first question, I created my own IsOptionalOrMatchesRegEx constraint:

public class IsOptionalOrMatchesRegEx : IRouteConstraint { private readonly string _regEx; public IsOptionalOrMatchesRegEx(string regEx) { _regEx = regEx; } public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) { var valueToCompare = values[parameterName].ToString(); if (string.IsNullOrEmpty(valueToCompare)) return true; return Regex.IsMatch(valueToCompare, _regEx); } } 

Then routes A and B can be expressed in one route:

  • url: "nl / blog / {articlepage}"
  • defaultvalues: new {articlepage = UrlParameter.Optional}
  • restrictions: new {articlepage = new IsOptionalOrMatchesRegEx (@ "\ d")

For question 2, I created an ExcludeConstraint:

 public class ExcludeConstraint : IRouteConstraint { private readonly List<string> _excludedList; public ExcludeConstraint(List<string> excludedList) { _excludedList = excludedList; } public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) { var valueToCompare = (string)values[parameterName]; return !_excludedList.Contains(valueToCompare); } } 

Route D could be changed as follows:

  • url: "nl / blog / {urltitle}"
  • constraints: new {urltitle = new ExcludeConstraint (new list () {"addarticle", "addcomment", "gettags"})}));
+4
source

Source: https://habr.com/ru/post/899945/


All Articles