Created
April 23, 2012 08:21
-
-
Save possan/2469492 to your computer and use it in GitHub Desktop.
Regex router mvc
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// collection.Add(new RegexRoute("(^|[a-z0-9/]*/)[0-9]+/[0-9]+/[0-9]+/[a-z0-9_.-]*__([0-9]+)/flush$", "sectionpath,pageid", new { controller = "misc", action = "flush" }, new MvcRouteHandler())); | |
public class RegexRoute : RouteBase | |
{ | |
private readonly string _match; | |
private readonly string _names; | |
private readonly RouteValueDictionary _defaults; | |
private readonly IRouteHandler _handler; | |
public RegexRoute(string match, string names, object defaults, IRouteHandler handler) | |
{ | |
_match = match; | |
_names = names; | |
_defaults = new RouteValueDictionary(defaults); | |
_handler = handler; | |
} | |
public RegexRoute(string match, object defaults, IRouteHandler handler) | |
{ | |
_match = match; | |
_names = ""; | |
_defaults = new RouteValueDictionary(defaults); | |
_handler = handler; | |
} | |
public override RouteData GetRouteData(HttpContextBase httpContext) | |
{ | |
var path = httpContext.Request.Path; | |
if (path.StartsWith("/")) | |
path = path.Substring(1); | |
var m = Regex.Match(path, _match, RegexOptions.IgnoreCase); | |
if (!m.Success) | |
return null; | |
var route = new RouteData(this, _handler); | |
foreach (var k in _defaults.Keys) | |
{ | |
if (route.Values.ContainsKey(k)) | |
route.Values[k] = _defaults[k]; | |
else | |
route.Values.Add(k, _defaults[k]); | |
} | |
var namelist = _names.Split(','); | |
for (var k = 1; k < m.Groups.Count; k++) | |
{ | |
if (route.Values.ContainsKey(namelist[k - 1])) | |
route.Values[namelist[k - 1]] = m.Groups[k].Value; | |
else | |
route.Values.Add(namelist[k - 1], m.Groups[k].Value); | |
} | |
return route; | |
} | |
public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values) | |
{ | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment