Reputation: 13531
I have URL's like:
for which I have defined routes:
Question 1: this works fine, but maybe there's a better solution with less routes?
Question 2: to add a new article, I have an action method AddArticle in BlogController. Of course, with the routes defined above, the url "/nl/blog/addarticle" would map to route D, where addarticle would be the urltitle which is not correct of course. Therefore I added the following route:
and so now the url "/nl/blog/_addarticle" maps to this route, and execute the correct action method. But I was wondering whether there is a better way to handle this?
Thanks for the advice.
Upvotes: 6
Views: 142
Reputation: 13531
Answers to my own questions:
For question one, I created a custom constraint IsOptionalOrMatchesRegEx:
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:
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 then be changed like:
Upvotes: 4