Route.cs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. //
  2. // Route.cs
  3. //
  4. // Author:
  5. // Atsushi Enomoto <[email protected]>
  6. //
  7. // Copyright (C) 2008 Novell Inc. http://novell.com
  8. //
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. using System;
  30. using System.Runtime.CompilerServices;
  31. using System.Security.Permissions;
  32. using System.Text.RegularExpressions;
  33. using System.Web;
  34. using System.Globalization;
  35. namespace System.Web.Routing
  36. {
  37. [TypeForwardedFrom ("System.Web.Routing, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=31bf3856ad364e35")]
  38. [AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
  39. [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
  40. public class Route : RouteBase
  41. {
  42. static readonly Type httpRequestBaseType = typeof (HttpRequestBase);
  43. PatternParser url;
  44. public RouteValueDictionary Constraints { get; set; }
  45. public RouteValueDictionary DataTokens { get; set; }
  46. public RouteValueDictionary Defaults { get; set; }
  47. public IRouteHandler RouteHandler { get; set; }
  48. public string Url {
  49. get { return url != null ? url.Url : String.Empty; }
  50. set { url = value != null ? new PatternParser (value) : new PatternParser (String.Empty); }
  51. }
  52. public Route (string url, IRouteHandler routeHandler)
  53. : this (url, null, routeHandler)
  54. {
  55. }
  56. public Route (string url, RouteValueDictionary defaults, IRouteHandler routeHandler)
  57. : this (url, defaults, null, routeHandler)
  58. {
  59. }
  60. public Route (string url, RouteValueDictionary defaults, RouteValueDictionary constraints, IRouteHandler routeHandler)
  61. : this (url, defaults, constraints, null, routeHandler)
  62. {
  63. }
  64. public Route (string url, RouteValueDictionary defaults, RouteValueDictionary constraints, RouteValueDictionary dataTokens, IRouteHandler routeHandler)
  65. {
  66. Url = url;
  67. Defaults = defaults;
  68. Constraints = constraints;
  69. DataTokens = dataTokens;
  70. RouteHandler = routeHandler;
  71. }
  72. public override RouteData GetRouteData (HttpContextBase httpContext)
  73. {
  74. var path = httpContext.Request.AppRelativeCurrentExecutionFilePath;
  75. var pathInfo = httpContext.Request.PathInfo;
  76. if (!String.IsNullOrEmpty (pathInfo))
  77. path += pathInfo;
  78. // probably code like this causes ArgumentOutOfRangeException under .NET.
  79. // It somehow allows such path that is completely equivalent to the Url. Dunno why.
  80. if (Url != path && path.Substring (0, 2) != "~/")
  81. return null;
  82. path = path.Substring (2);
  83. var values = url.Match (path, Defaults);
  84. if (values == null)
  85. return null;
  86. if (!ProcessConstraints (httpContext, values, RouteDirection.IncomingRequest))
  87. return null;
  88. var rd = new RouteData (this, RouteHandler);
  89. RouteValueDictionary rdValues = rd.Values;
  90. foreach (var p in values)
  91. rdValues.Add (p.Key, p.Value);
  92. RouteValueDictionary dataTokens = DataTokens;
  93. if (dataTokens != null) {
  94. RouteValueDictionary rdDataTokens = rd.DataTokens;
  95. foreach (var token in dataTokens)
  96. rdDataTokens.Add (token.Key, token.Value);
  97. }
  98. return rd;
  99. }
  100. public override VirtualPathData GetVirtualPath (RequestContext requestContext, RouteValueDictionary values)
  101. {
  102. if (requestContext == null)
  103. throw new ArgumentNullException ("requestContext");
  104. if (url == null)
  105. return new VirtualPathData (this, String.Empty);
  106. // null values is allowed.
  107. // if (values == null)
  108. // values = requestContext.RouteData.Values;
  109. RouteValueDictionary usedValues;
  110. string resultUrl = url.BuildUrl (this, requestContext, values, Constraints, out usedValues);
  111. if (resultUrl == null)
  112. return null;
  113. if (!ProcessConstraints (requestContext.HttpContext, usedValues, RouteDirection.UrlGeneration))
  114. return null;
  115. var result = new VirtualPathData (this, resultUrl);
  116. RouteValueDictionary dataTokens = DataTokens;
  117. if (dataTokens != null) {
  118. foreach (var item in dataTokens)
  119. result.DataTokens[item.Key] = item.Value;
  120. }
  121. return result;
  122. }
  123. private bool ProcessConstraintInternal (HttpContextBase httpContext, Route route, object constraint, string parameterName,
  124. RouteValueDictionary values, RouteDirection routeDirection, RequestContext reqContext,
  125. out bool invalidConstraint)
  126. {
  127. invalidConstraint = false;
  128. IRouteConstraint irc = constraint as IRouteConstraint;
  129. if (irc != null)
  130. return irc.Match (httpContext, route, parameterName, values, routeDirection);
  131. string s = constraint as string;
  132. if (s != null) {
  133. string v = null;
  134. object o;
  135. // NOTE: If constraint was not an IRouteConstraint, is is asumed
  136. // to be an object 'convertible' to string, or at least this is how
  137. // ASP.NET seems to work by the tests i've done latelly. (pruiz)
  138. if (values != null && values.TryGetValue (parameterName, out o))
  139. v = Convert.ToString (o, CultureInfo.InvariantCulture);
  140. if (!String.IsNullOrEmpty (v))
  141. return MatchConstraintRegex (v, s);
  142. else if (reqContext != null) {
  143. RouteData rd = reqContext != null ? reqContext.RouteData : null;
  144. RouteValueDictionary rdValues = rd != null ? rd.Values : null;
  145. if (rdValues == null || rdValues.Count == 0)
  146. return false;
  147. if (!rdValues.TryGetValue (parameterName, out o))
  148. return false;
  149. v = Convert.ToString (o, CultureInfo.InvariantCulture);
  150. if (String.IsNullOrEmpty (v))
  151. return false;
  152. return MatchConstraintRegex (v, s);
  153. }
  154. return false;
  155. }
  156. invalidConstraint = true;
  157. return false;
  158. }
  159. static bool MatchConstraintRegex (string value, string constraint)
  160. {
  161. int len = constraint.Length;
  162. if (len > 0) {
  163. // Bug #651966 - regexp constraints must be treated
  164. // as absolute expressions
  165. if (constraint [0] != '^') {
  166. constraint = "^" + constraint;
  167. len++;
  168. }
  169. if (constraint [len - 1] != '$')
  170. constraint += "$";
  171. }
  172. return Regex.IsMatch (value, constraint, RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.Compiled);
  173. }
  174. protected virtual bool ProcessConstraint (HttpContextBase httpContext, object constraint, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
  175. {
  176. if (parameterName == null)
  177. throw new ArgumentNullException ("parameterName");
  178. // .NET "compatibility"
  179. if (values == null)
  180. throw new NullReferenceException ();
  181. RequestContext reqContext;
  182. reqContext = SafeGetContext (httpContext != null ? httpContext.Request : null);
  183. bool invalidConstraint;
  184. bool ret = ProcessConstraintInternal (httpContext, this, constraint, parameterName, values, routeDirection, reqContext, out invalidConstraint);
  185. if (invalidConstraint)
  186. throw new InvalidOperationException (
  187. String.Format (
  188. "Constraint parameter '{0}' on the route with URL '{1}' must have a string value type or be a type which implements IRouteConstraint",
  189. parameterName, Url
  190. )
  191. );
  192. return ret;
  193. }
  194. private bool ProcessConstraints (HttpContextBase httpContext, RouteValueDictionary values, RouteDirection routeDirection)
  195. {
  196. var constraints = Constraints;
  197. if (Constraints != null) {
  198. foreach (var p in constraints)
  199. if (!ProcessConstraint (httpContext, p.Value, p.Key, values, routeDirection))
  200. return false;
  201. }
  202. return true;
  203. }
  204. RequestContext SafeGetContext (HttpRequestBase req)
  205. {
  206. if (req == null || req.GetType () != httpRequestBaseType)
  207. return null;
  208. return req.RequestContext;
  209. }
  210. }
  211. }