public string BuildUrl(Route route, RequestContext requestContext, RouteValueDictionary userValues, RouteValueDictionary constraints, out RouteValueDictionary usedValues) { usedValues = null; if (requestContext == null) { return(null); } RouteData routeData = requestContext.RouteData; var currentValues = routeData.Values ?? new RouteValueDictionary(); var values = userValues ?? new RouteValueDictionary(); var defaultValues = (route != null ? route.Defaults : null) ?? new RouteValueDictionary(); // The set of values we should be using when generating the URL in this route var acceptedValues = new RouteValueDictionary(); // Keep track of which new values have been used HashSet <string> unusedNewValues = new HashSet <string> (values.Keys, StringComparer.OrdinalIgnoreCase); // This route building logic is based on System.Web.Http's Routing code (which is Apache Licensed by MS) // and which can be found at mono's external/aspnetwebstack/src/System.Web.Http/Routing/HttpParsedRoute.cs // Hopefully this will ensure a much higher compatiblity with MS.NET's System.Web.Routing logic. (pruiz) #region Step 1: Get the list of values we're going to use to match and generate this URL // Find out which entries in the URL are valid for the URL we want to generate. // If the URL had ordered parameters a="1", b="2", c="3" and the new values // specified that b="9", then we need to invalidate everything after it. The new // values should then be a="1", b="9", c=<no value>. foreach (var item in parameterNames) { var parameterName = item.Key; object newParameterValue; bool hasNewParameterValue = values.TryGetValue(parameterName, out newParameterValue); if (hasNewParameterValue) { unusedNewValues.Remove(parameterName); } object currentParameterValue; bool hasCurrentParameterValue = currentValues.TryGetValue(parameterName, out currentParameterValue); if (hasNewParameterValue && hasCurrentParameterValue) { if (!ParametersAreEqual(currentParameterValue, newParameterValue)) { // Stop copying current values when we find one that doesn't match break; } } // If the parameter is a match, add it to the list of values we will use for URL generation if (hasNewParameterValue) { if (ParameterIsNonEmpty(newParameterValue)) { acceptedValues.Add(parameterName, newParameterValue); } } else { if (hasCurrentParameterValue) { acceptedValues.Add(parameterName, currentParameterValue); } } } // Add all remaining new values to the list of values we will use for URL generation foreach (var newValue in values) { if (ParameterIsNonEmpty(newValue.Value) && !acceptedValues.ContainsKey(newValue.Key)) { acceptedValues.Add(newValue.Key, newValue.Value); } } // Add all current values that aren't in the URL at all foreach (var currentValue in currentValues) { if (!acceptedValues.ContainsKey(currentValue.Key) && !parameterNames.ContainsKey(currentValue.Key)) { acceptedValues.Add(currentValue.Key, currentValue.Value); } } // Add all remaining default values from the route to the list of values we will use for URL generation foreach (var item in parameterNames) { object defaultValue; if (!acceptedValues.ContainsKey(item.Key) && !IsParameterRequired(item.Key, defaultValues, out defaultValue)) { // Add the default value only if there isn't already a new value for it and // only if it actually has a default value, which we determine based on whether // the parameter value is required. acceptedValues.Add(item.Key, defaultValue); } } // All required parameters in this URL must have values from somewhere (i.e. the accepted values) foreach (var item in parameterNames) { object defaultValue; if (IsParameterRequired(item.Key, defaultValues, out defaultValue) && !acceptedValues.ContainsKey(item.Key)) { // If the route parameter value is required that means there's // no default value, so if there wasn't a new value for it // either, this route won't match. return(null); } } // All other default values must match if they are explicitly defined in the new values var otherDefaultValues = new RouteValueDictionary(defaultValues); foreach (var item in parameterNames) { otherDefaultValues.Remove(item.Key); } foreach (var defaultValue in otherDefaultValues) { object value; if (values.TryGetValue(defaultValue.Key, out value)) { unusedNewValues.Remove(defaultValue.Key); if (!ParametersAreEqual(value, defaultValue.Value)) { // If there is a non-parameterized value in the route and there is a // new value for it and it doesn't match, this route won't match. return(null); } } } #endregion #region Step 2: If the route is a match generate the appropriate URL var uri = new StringBuilder(); var pendingParts = new StringBuilder(); var pendingPartsAreAllSafe = false; bool blockAllUriAppends = false; var allSegments = new List <PatternSegment?> (); // Build a list of segments plus separators we can use as template. foreach (var segment in segments) { if (allSegments.Count > 0) { allSegments.Add(null); // separator exposed as null. } allSegments.Add(segment); } // Finally loop thru al segment-templates building the actual uri. foreach (var item in allSegments) { var segment = item.GetValueOrDefault(); // If segment is a separator.. if (item == null) { if (pendingPartsAreAllSafe) { // Accept if (pendingParts.Length > 0) { if (blockAllUriAppends) { return(null); } // Append any pending literals to the URL uri.Append(pendingParts.ToString()); pendingParts.Length = 0; } } pendingPartsAreAllSafe = false; // Guard against appending multiple separators for empty segments if (pendingParts.Length > 0 && pendingParts[pendingParts.Length - 1] == '/') { // Dev10 676725: Route should not be matched if that causes mismatched tokens // Dev11 86819: We will allow empty matches if all subsequent segments are null if (blockAllUriAppends) { return(null); } // Append any pending literals to the URI (without the trailing slash) and prevent any future appends uri.Append(pendingParts.ToString(0, pendingParts.Length - 1)); pendingParts.Length = 0; } else { pendingParts.Append("/"); } #if false } else if (segment.AllLiteral) { // Spezial (optimized) case: all elements of segment are literals. pendingPartsAreAllSafe = true; foreach (var tk in segment.Tokens) { pendingParts.Append(tk.Name); } #endif } else { // Segments are treated as all-or-none. We should never output a partial segment. // If we add any subsegment of this segment to the generated URL, we have to add // the complete match. For example, if the subsegment is "{p1}-{p2}.xml" and we // used a value for {p1}, we have to output the entire segment up to the next "/". // Otherwise we could end up with the partial segment "v1" instead of the entire // segment "v1-v2.xml". bool addedAnySubsegments = false; foreach (var token in segment.Tokens) { if (token.Type == PatternTokenType.Literal) { // If it's a literal we hold on to it until we are sure we need to add it pendingPartsAreAllSafe = true; pendingParts.Append(token.Name); } else { if (token.Type == PatternTokenType.Standard) { if (pendingPartsAreAllSafe) { // Accept if (pendingParts.Length > 0) { if (blockAllUriAppends) { return(null); } // Append any pending literals to the URL uri.Append(pendingParts.ToString()); pendingParts.Length = 0; addedAnySubsegments = true; } } pendingPartsAreAllSafe = false; // If it's a parameter, get its value object acceptedParameterValue; bool hasAcceptedParameterValue = acceptedValues.TryGetValue(token.Name, out acceptedParameterValue); if (hasAcceptedParameterValue) { unusedNewValues.Remove(token.Name); } object defaultParameterValue; defaultValues.TryGetValue(token.Name, out defaultParameterValue); if (ParametersAreEqual(acceptedParameterValue, defaultParameterValue)) { // If the accepted value is the same as the default value, mark it as pending since // we won't necessarily add it to the URL we generate. pendingParts.Append(Convert.ToString(acceptedParameterValue, CultureInfo.InvariantCulture)); } else { if (blockAllUriAppends) { return(null); } // Add the new part to the URL as well as any pending parts if (pendingParts.Length > 0) { // Append any pending literals to the URL uri.Append(pendingParts.ToString()); pendingParts.Length = 0; } uri.Append(Convert.ToString(acceptedParameterValue, CultureInfo.InvariantCulture)); addedAnySubsegments = true; } } else { Debug.Fail("Invalid path subsegment type"); } } } if (addedAnySubsegments) { // See comment above about why we add the pending parts if (pendingParts.Length > 0) { if (blockAllUriAppends) { return(null); } // Append any pending literals to the URL uri.Append(pendingParts.ToString()); pendingParts.Length = 0; } } } } if (pendingPartsAreAllSafe) { // Accept if (pendingParts.Length > 0) { if (blockAllUriAppends) { return(null); } // Append any pending literals to the URI uri.Append(pendingParts.ToString()); } } // Process constraints keys if (constraints != null) { // If there are any constraints, mark all the keys as being used so that we don't // generate query string items for custom constraints that don't appear as parameters // in the URI format. foreach (var constraintsItem in constraints) { unusedNewValues.Remove(constraintsItem.Key); } } // Encode the URI before we append the query string, otherwise we would double encode the query string var encodedUri = new StringBuilder(); encodedUri.Append(UriEncode(uri.ToString())); uri = encodedUri; // Add remaining new values as query string parameters to the URI if (unusedNewValues.Count > 0) { // Generate the query string bool firstParam = true; foreach (string unusedNewValue in unusedNewValues) { object value; if (acceptedValues.TryGetValue(unusedNewValue, out value)) { uri.Append(firstParam ? '?' : '&'); firstParam = false; uri.Append(Uri.EscapeDataString(unusedNewValue)); uri.Append('='); uri.Append(Uri.EscapeDataString(Convert.ToString(value, CultureInfo.InvariantCulture))); } } } #endregion usedValues = acceptedValues; return(uri.ToString()); }
private bool MatchContentPathSegment(ContentPathSegment routeSegment, string requestPathSegment, RouteValueDictionary defaultValues, RouteValueDictionary matchedValues) { if (string.IsNullOrEmpty(requestPathSegment)) { if (routeSegment.Subsegments.Count <= 1) { object obj2; ParameterSubsegment subsegment = routeSegment.Subsegments[0] as ParameterSubsegment; if (subsegment == null) { return(false); } if (defaultValues.TryGetValue(subsegment.ParameterName, out obj2)) { matchedValues.Add(subsegment.ParameterName, obj2); return(true); } } return(false); } int length = requestPathSegment.Length; int num2 = routeSegment.Subsegments.Count - 1; ParameterSubsegment subsegment2 = null; LiteralSubsegment subsegment3 = null; while (num2 >= 0) { int num3 = length; ParameterSubsegment subsegment4 = routeSegment.Subsegments[num2] as ParameterSubsegment; if (subsegment4 != null) { subsegment2 = subsegment4; } else { LiteralSubsegment subsegment5 = routeSegment.Subsegments[num2] as LiteralSubsegment; if (subsegment5 != null) { subsegment3 = subsegment5; int startIndex = length - 1; if (subsegment2 != null) { startIndex--; } if (startIndex < 0) { return(false); } int num5 = requestPathSegment.LastIndexOf(subsegment5.Literal, startIndex, StringComparison.OrdinalIgnoreCase); if (num5 == -1) { return(false); } if ((num2 == (routeSegment.Subsegments.Count - 1)) && ((num5 + subsegment5.Literal.Length) != requestPathSegment.Length)) { return(false); } num3 = num5; } } if ((subsegment2 != null) && (((subsegment3 != null) && (subsegment4 == null)) || (num2 == 0))) { int num6; int num7; if (subsegment3 == null) { if (num2 == 0) { num6 = 0; } else { num6 = num3 + subsegment3.Literal.Length; } num7 = length; } else if ((num2 == 0) && (subsegment4 != null)) { num6 = 0; num7 = length; } else { num6 = num3 + subsegment3.Literal.Length; num7 = length - num6; } string str = requestPathSegment.Substring(num6, num7); if (string.IsNullOrEmpty(str)) { return(false); } matchedValues.Add(subsegment2.ParameterName, str); subsegment2 = null; subsegment3 = null; } length = num3; num2--; } if (length != 0) { return(routeSegment.Subsegments[0] is ParameterSubsegment); } return(true); }
public bool BuildUrl(Route route, RequestContext requestContext, RouteValueDictionary userValues, out string value) { value = null; if (requestContext == null) { return(false); } RouteData routeData = requestContext.RouteData; RouteValueDictionary defaultValues = route != null ? route.Defaults : null; RouteValueDictionary ambientValues = routeData.Values; if (defaultValues != null && defaultValues.Count == 0) { defaultValues = null; } if (ambientValues != null && ambientValues.Count == 0) { ambientValues = null; } if (userValues != null && userValues.Count == 0) { userValues = null; } // Check URL parameters // It is allowed to take ambient values for required parameters if: // // - there are no default values provided // - the default values dictionary contains at least one required // parameter value // bool canTakeFromAmbient; if (defaultValues == null) { canTakeFromAmbient = true; } else { canTakeFromAmbient = false; foreach (KeyValuePair <string, bool> de in parameterNames) { if (defaultValues.ContainsKey(de.Key)) { canTakeFromAmbient = true; break; } } } bool allMustBeInUserValues = false; foreach (KeyValuePair <string, bool> de in parameterNames) { string parameterName = de.Key; // Is the parameter required? if (defaultValues == null || !defaultValues.ContainsKey(parameterName)) { // Yes, it is required (no value in defaults) // Has the user provided value for it? if (userValues == null || !userValues.ContainsKey(parameterName)) { if (allMustBeInUserValues) { return(false); // partial override => no match } if (!canTakeFromAmbient || ambientValues == null || !ambientValues.ContainsKey(parameterName)) { return(false); // no value provided => no match } } else if (canTakeFromAmbient) { allMustBeInUserValues = true; } } } // Check for non-url parameters if (defaultValues != null) { foreach (var de in defaultValues) { string parameterName = de.Key; if (parameterNames.ContainsKey(parameterName)) { continue; } object parameterValue = null; // Has the user specified value for this parameter and, if // yes, is it the same as the one in defaults? if (userValues != null && userValues.TryGetValue(parameterName, out parameterValue)) { object defaultValue = de.Value; if (defaultValue is string && parameterValue is string) { if (String.Compare((string)defaultValue, (string)parameterValue, StringComparison.Ordinal) != 0) { return(false); // different value => no match } } else if (defaultValue != parameterValue) { return(false); // different value => no match } } } } // Check the constraints RouteValueDictionary constraints = route != null ? route.Constraints : null; if (constraints != null && constraints.Count > 0) { HttpContextBase context = requestContext.HttpContext; bool invalidConstraint; foreach (var de in constraints) { if (!Route.ProcessConstraintInternal(context, route, de.Value, de.Key, userValues, RouteDirection.UrlGeneration, requestContext, out invalidConstraint) || invalidConstraint) { return(false); // constraint not met => no match } } } // We're a match, generate the URL var ret = new StringBuilder(); bool canTrim = true; // Going in reverse order, so that we can trim without much ado int tokensCount = tokens.Length - 1; for (int i = tokensCount; i >= 0; i--) { PatternToken token = tokens [i]; if (token == null) { if (i < tokensCount && ret.Length > 0 && ret [0] != '/') { ret.Insert(0, '/'); } continue; } if (token.Type == PatternTokenType.Literal) { ret.Insert(0, token.Name); continue; } string parameterName = token.Name; object tokenValue; #if SYSTEMCORE_DEP if (userValues.GetValue(parameterName, out tokenValue)) { if (!defaultValues.Has(parameterName, tokenValue)) { canTrim = false; if (tokenValue != null) { ret.Insert(0, tokenValue.ToString()); } continue; } if (!canTrim && tokenValue != null) { ret.Insert(0, tokenValue.ToString()); } continue; } if (defaultValues.GetValue(parameterName, out tokenValue)) { object ambientTokenValue; if (ambientValues.GetValue(parameterName, out ambientTokenValue)) { tokenValue = ambientTokenValue; } if (!canTrim && tokenValue != null) { ret.Insert(0, tokenValue.ToString()); } continue; } canTrim = false; if (ambientValues.GetValue(parameterName, out tokenValue)) { if (tokenValue != null) { ret.Insert(0, tokenValue.ToString()); } continue; } #endif } // All the values specified in userValues that aren't part of the original // URL, the constraints or defaults collections are treated as overflow // values - they are appended as query parameters to the URL if (userValues != null) { bool first = true; foreach (var de in userValues) { string parameterName = de.Key; #if SYSTEMCORE_DEP if (parameterNames.ContainsKey(parameterName) || defaultValues.Has(parameterName) || constraints.Has(parameterName)) { continue; } #endif object parameterValue = de.Value; if (parameterValue == null) { continue; } var parameterValueAsString = parameterValue as string; if (parameterValueAsString != null && parameterValueAsString.Length == 0) { continue; } if (first) { ret.Append('?'); first = false; } else { ret.Append('&'); } ret.Append(Uri.EscapeDataString(parameterName)); ret.Append('='); if (parameterValue != null) { ret.Append(Uri.EscapeDataString(de.Value.ToString())); } } } value = ret.ToString(); return(true); }
public BoundUrl Bind(RouteValueDictionary currentValues, RouteValueDictionary values, RouteValueDictionary defaultValues, RouteValueDictionary constraints) { if (currentValues == null) { currentValues = new RouteValueDictionary(); } if (values == null) { values = new RouteValueDictionary(); } if (defaultValues == null) { defaultValues = new RouteValueDictionary(); } RouteValueDictionary acceptedValues = new RouteValueDictionary(); HashSet <string> unusedNewValues = new HashSet <string>(values.Keys, StringComparer.OrdinalIgnoreCase); ForEachParameter(this.PathSegments, delegate(ParameterSubsegment parameterSubsegment) { object obj2; object obj3; string key = parameterSubsegment.ParameterName; bool flag = values.TryGetValue(key, out obj2); if (flag) { unusedNewValues.Remove(key); } bool flag2 = currentValues.TryGetValue(key, out obj3); if ((flag && flag2) && !RoutePartsEqual(obj3, obj2)) { return(false); } if (flag) { if (IsRoutePartNonEmpty(obj2)) { acceptedValues.Add(key, obj2); } } else if (flag2) { acceptedValues.Add(key, obj3); } return(true); }); foreach (KeyValuePair <string, object> pair in values) { if (IsRoutePartNonEmpty(pair.Value) && !acceptedValues.ContainsKey(pair.Key)) { acceptedValues.Add(pair.Key, pair.Value); } } foreach (KeyValuePair <string, object> pair2 in currentValues) { string str = pair2.Key; if (!acceptedValues.ContainsKey(str) && (GetParameterSubsegment(this.PathSegments, str) == null)) { acceptedValues.Add(str, pair2.Value); } } ForEachParameter(this.PathSegments, delegate(ParameterSubsegment parameterSubsegment) { object obj2; if (!acceptedValues.ContainsKey(parameterSubsegment.ParameterName) && !IsParameterRequired(parameterSubsegment, defaultValues, out obj2)) { acceptedValues.Add(parameterSubsegment.ParameterName, obj2); } return(true); }); if (!ForEachParameter(this.PathSegments, delegate(ParameterSubsegment parameterSubsegment) { object obj2; if (IsParameterRequired(parameterSubsegment, defaultValues, out obj2) && !acceptedValues.ContainsKey(parameterSubsegment.ParameterName)) { return(false); } return(true); })) { return(null); } RouteValueDictionary otherDefaultValues = new RouteValueDictionary(defaultValues); ForEachParameter(this.PathSegments, delegate(ParameterSubsegment parameterSubsegment) { otherDefaultValues.Remove(parameterSubsegment.ParameterName); return(true); }); foreach (KeyValuePair <string, object> pair3 in otherDefaultValues) { object obj2; if (values.TryGetValue(pair3.Key, out obj2)) { unusedNewValues.Remove(pair3.Key); if (!RoutePartsEqual(obj2, pair3.Value)) { return(null); } } } StringBuilder builder = new StringBuilder(); StringBuilder builder2 = new StringBuilder(); bool flag2_1 = false; for (int i = 0; i < this.PathSegments.Count; i++) { PathSegment segment = this.PathSegments[i]; if (segment is SeparatorPathSegment) { if (flag2_1 && (builder2.Length > 0)) { builder.Append(builder2.ToString()); builder2.Length = 0; } flag2_1 = false; if ((builder2.Length > 0) && (builder2[builder2.Length - 1] == '/')) { return(null); } builder2.Append("/"); } else { ContentPathSegment segment2 = segment as ContentPathSegment; if (segment2 != null) { bool flag3 = false; foreach (PathSubsegment subsegment2 in segment2.Subsegments) { LiteralSubsegment subsegment3 = subsegment2 as LiteralSubsegment; if (subsegment3 != null) { flag2_1 = true; builder2.Append(UrlEncode(subsegment3.Literal)); } else { ParameterSubsegment subsegment4 = subsegment2 as ParameterSubsegment; if (subsegment4 != null) { object obj3; object obj4; if (flag2_1 && (builder2.Length > 0)) { builder.Append(builder2.ToString()); builder2.Length = 0; flag3 = true; } flag2_1 = false; if (acceptedValues.TryGetValue(subsegment4.ParameterName, out obj3)) { unusedNewValues.Remove(subsegment4.ParameterName); } defaultValues.TryGetValue(subsegment4.ParameterName, out obj4); if (RoutePartsEqual(obj3, obj4)) { builder2.Append(UrlEncode(Convert.ToString(obj3, CultureInfo.InvariantCulture))); continue; } if (builder2.Length > 0) { builder.Append(builder2.ToString()); builder2.Length = 0; } builder.Append(UrlEncode(Convert.ToString(obj3, CultureInfo.InvariantCulture))); flag3 = true; } } } if (flag3 && (builder2.Length > 0)) { builder.Append(builder2.ToString()); builder2.Length = 0; } } } } if (flag2_1 && (builder2.Length > 0)) { builder.Append(builder2.ToString()); } if (constraints != null) { foreach (KeyValuePair <string, object> pair4 in constraints) { unusedNewValues.Remove(pair4.Key); } } if (unusedNewValues.Count > 0) { bool flag5 = true; foreach (string str2 in unusedNewValues) { object obj5; if (acceptedValues.TryGetValue(str2, out obj5)) { builder.Append(flag5 ? '?' : '&'); flag5 = false; builder.Append(Uri.EscapeDataString(str2)); builder.Append('='); builder.Append(Uri.EscapeDataString(Convert.ToString(obj5, CultureInfo.InvariantCulture))); } } } return(new BoundUrl { Url = builder.ToString(), Values = acceptedValues }); }
private bool MatchContentPathSegment(ContentPathSegment routeSegment, string requestPathSegment, RouteValueDictionary defaultValues, RouteValueDictionary matchedValues) { if (String.IsNullOrEmpty(requestPathSegment)) { // If there's no data to parse, we must have exactly one parameter segment and no other segments - otherwise no match if (routeSegment.Subsegments.Count > 1) { return(false); } ParameterSubsegment parameterSubsegment = routeSegment.Subsegments[0] as ParameterSubsegment; if (parameterSubsegment == null) { return(false); } // We must have a default value since there's no value in the request URL object parameterValue; if (defaultValues.TryGetValue(parameterSubsegment.ParameterName, out parameterValue)) { // If there's a default value for this parameter, use that default value matchedValues.Add(parameterSubsegment.ParameterName, parameterValue); return(true); } else { // If there's no default value, this segment doesn't match return(false); } } // Find last literal segment and get its last index in the string int lastIndex = requestPathSegment.Length; int indexOfLastSegmentUsed = routeSegment.Subsegments.Count - 1; ParameterSubsegment parameterNeedsValue = null; // Keeps track of a parameter segment that is pending a value LiteralSubsegment lastLiteral = null; // Keeps track of the left-most literal we've encountered while (indexOfLastSegmentUsed >= 0) { int newLastIndex = lastIndex; ParameterSubsegment parameterSubsegment = routeSegment.Subsegments[indexOfLastSegmentUsed] as ParameterSubsegment; if (parameterSubsegment != null) { // Hold on to the parameter so that we can fill it in when we locate the next literal parameterNeedsValue = parameterSubsegment; } else { LiteralSubsegment literalSubsegment = routeSegment.Subsegments[indexOfLastSegmentUsed] as LiteralSubsegment; if (literalSubsegment != null) { lastLiteral = literalSubsegment; int startIndex = lastIndex - 1; // If we have a pending parameter subsegment, we must leave at least one character for that if (parameterNeedsValue != null) { startIndex--; } if (startIndex < 0) { return(false); } int indexOfLiteral = requestPathSegment.LastIndexOf(literalSubsegment.Literal, startIndex, StringComparison.OrdinalIgnoreCase); if (indexOfLiteral == -1) { // If we couldn't find this literal index, this segment cannot match return(false); } // If the first subsegment is a literal, it must match at the right-most extent of the request URL. // Without this check if your route had "/Foo/" we'd match the request URL "/somethingFoo/". // This check is related to the check we do at the very end of this function. if (indexOfLastSegmentUsed == (routeSegment.Subsegments.Count - 1)) { if ((indexOfLiteral + literalSubsegment.Literal.Length) != requestPathSegment.Length) { return(false); } } newLastIndex = indexOfLiteral; } else { Debug.Fail("Invalid path segment type"); } } if ((parameterNeedsValue != null) && (((lastLiteral != null) && (parameterSubsegment == null)) || (indexOfLastSegmentUsed == 0))) { // If we have a pending parameter that needs a value, grab that value int parameterStartIndex; int parameterTextLength; if (lastLiteral == null) { if (indexOfLastSegmentUsed == 0) { parameterStartIndex = 0; } else { parameterStartIndex = newLastIndex; Debug.Fail("indexOfLastSegementUsed should always be 0 from the check above"); } parameterTextLength = lastIndex; } else { // If we're getting a value for a parameter that is somewhere in the middle of the segment if ((indexOfLastSegmentUsed == 0) && (parameterSubsegment != null)) { parameterStartIndex = 0; parameterTextLength = lastIndex; } else { parameterStartIndex = newLastIndex + lastLiteral.Literal.Length; parameterTextLength = lastIndex - parameterStartIndex; } } string parameterValueString = requestPathSegment.Substring(parameterStartIndex, parameterTextLength); if (String.IsNullOrEmpty(parameterValueString)) { // If we're here that means we have a segment that contains multiple sub-segments. // For these segments all parameters must have non-empty values. If the parameter // has an empty value it's not a match. return(false); } else { // If there's a value in the segment for this parameter, use the subsegment value matchedValues.Add(parameterNeedsValue.ParameterName, parameterValueString); } parameterNeedsValue = null; lastLiteral = null; } lastIndex = newLastIndex; indexOfLastSegmentUsed--; } // If the last subsegment is a parameter, it's OK that we didn't parse all the way to the left extent of // the string since the parameter will have consumed all the remaining text anyway. If the last subsegment // is a literal then we *must* have consumed the entire text in that literal. Otherwise we end up matching // the route "Foo" to the request URL "somethingFoo". Thus we have to check that we parsed the *entire* // request URL in order for it to be a match. // This check is related to the check we do earlier in this function for LiteralSubsegments. return((lastIndex == 0) || (routeSegment.Subsegments[0] is ParameterSubsegment)); }
public BoundUrl Bind(RouteValueDictionary currentValues, RouteValueDictionary values, RouteValueDictionary defaultValues, RouteValueDictionary constraints) { if (currentValues == null) { currentValues = new RouteValueDictionary(); } if (values == null) { values = new RouteValueDictionary(); } if (defaultValues == null) { defaultValues = new RouteValueDictionary(); } // The set of values we should be using when generating the URL in this route RouteValueDictionary acceptedValues = new RouteValueDictionary(); // Keep track of which new values have been used HashSet <string> unusedNewValues = new HashSet <string>(values.Keys, StringComparer.OrdinalIgnoreCase); // Step 1: Get the list of values we're going to try to use to match and generate this URL // Find out which entries in the URL are valid for the URL we want to generate. // If the URL had ordered parameters a="1", b="2", c="3" and the new values // specified that b="9", then we need to invalidate everything after it. The new // values should then be a="1", b="9", c=<no value>. ForEachParameter(PathSegments, delegate(ParameterSubsegment parameterSubsegment) { // If it's a parameter subsegment, examine the current value to see if it matches the new value string parameterName = parameterSubsegment.ParameterName; object newParameterValue; bool hasNewParameterValue = values.TryGetValue(parameterName, out newParameterValue); if (hasNewParameterValue) { unusedNewValues.Remove(parameterName); } object currentParameterValue; bool hasCurrentParameterValue = currentValues.TryGetValue(parameterName, out currentParameterValue); if (hasNewParameterValue && hasCurrentParameterValue) { if (!RoutePartsEqual(currentParameterValue, newParameterValue)) { // Stop copying current values when we find one that doesn't match return(false); } } // If the parameter is a match, add it to the list of values we will use for URL generation if (hasNewParameterValue) { if (IsRoutePartNonEmpty(newParameterValue)) { acceptedValues.Add(parameterName, newParameterValue); } } else { if (hasCurrentParameterValue) { acceptedValues.Add(parameterName, currentParameterValue); } } return(true); }); // Add all remaining new values to the list of values we will use for URL generation foreach (var newValue in values) { if (IsRoutePartNonEmpty(newValue.Value)) { if (!acceptedValues.ContainsKey(newValue.Key)) { acceptedValues.Add(newValue.Key, newValue.Value); } } } // Add all current values that aren't in the URL at all foreach (var currentValue in currentValues) { string parameterName = currentValue.Key; if (!acceptedValues.ContainsKey(parameterName)) { ParameterSubsegment parameterSubsegment = GetParameterSubsegment(PathSegments, parameterName); if (parameterSubsegment == null) { acceptedValues.Add(parameterName, currentValue.Value); } } } // Add all remaining default values from the route to the list of values we will use for URL generation ForEachParameter(PathSegments, delegate(ParameterSubsegment parameterSubsegment) { if (!acceptedValues.ContainsKey(parameterSubsegment.ParameterName)) { object defaultValue; if (!IsParameterRequired(parameterSubsegment, defaultValues, out defaultValue)) { // Add the default value only if there isn't already a new value for it and // only if it actually has a default value, which we determine based on whether // the parameter value is required. acceptedValues.Add(parameterSubsegment.ParameterName, defaultValue); } } return(true); }); // All required parameters in this URL must have values from somewhere (i.e. the accepted values) bool hasAllRequiredValues = ForEachParameter(PathSegments, delegate(ParameterSubsegment parameterSubsegment) { object defaultValue; if (IsParameterRequired(parameterSubsegment, defaultValues, out defaultValue)) { if (!acceptedValues.ContainsKey(parameterSubsegment.ParameterName)) { // If the route parameter value is required that means there's // no default value, so if there wasn't a new value for it // either, this route won't match. return(false); } } return(true); }); if (!hasAllRequiredValues) { return(null); } // All other default values must match if they are explicitly defined in the new values RouteValueDictionary otherDefaultValues = new RouteValueDictionary(defaultValues); ForEachParameter(PathSegments, delegate(ParameterSubsegment parameterSubsegment) { otherDefaultValues.Remove(parameterSubsegment.ParameterName); return(true); }); foreach (var defaultValue in otherDefaultValues) { object value; if (values.TryGetValue(defaultValue.Key, out value)) { unusedNewValues.Remove(defaultValue.Key); if (!RoutePartsEqual(value, defaultValue.Value)) { // If there is a non-parameterized value in the route and there is a // new value for it and it doesn't match, this route won't match. return(null); } } } // Step 2: If the route is a match generate the appropriate URL StringBuilder url = new StringBuilder(); StringBuilder pendingParts = new StringBuilder(); bool pendingPartsAreAllSafe = false; bool blockAllUrlAppends = false; for (int i = 0; i < PathSegments.Count; i++) { PathSegment pathSegment = PathSegments[i]; // parsedRouteUrlPart if (pathSegment is SeparatorPathSegment) { if (pendingPartsAreAllSafe) { // Accept if (pendingParts.Length > 0) { if (blockAllUrlAppends) { return(null); } // Append any pending literals to the URL url.Append(pendingParts.ToString()); pendingParts.Length = 0; } } pendingPartsAreAllSafe = false; // Guard against appending multiple separators for empty segements if (pendingParts.Length > 0 && pendingParts[pendingParts.Length - 1] == '/') { // Dev10 676725: Route should not be matched if that causes mismatched tokens // Dev11 86819: We will allow empty matches if all subsequent segments are null if (blockAllUrlAppends) { return(null); } // Append any pending literals to the URL(without the trailing slash) and prevent any future appends url.Append(pendingParts.ToString(0, pendingParts.Length - 1)); pendingParts.Length = 0; blockAllUrlAppends = true; } else { pendingParts.Append("/"); } } else { ContentPathSegment contentPathSegment = pathSegment as ContentPathSegment; if (contentPathSegment != null) { // Segments are treated as all-or-none. We should never output a partial segment. // If we add any subsegment of this segment to the generated URL, we have to add // the complete match. For example, if the subsegment is "{p1}-{p2}.xml" and we // used a value for {p1}, we have to output the entire segment up to the next "/". // Otherwise we could end up with the partial segment "v1" instead of the entire // segment "v1-v2.xml". bool addedAnySubsegments = false; foreach (PathSubsegment subsegment in contentPathSegment.Subsegments) { LiteralSubsegment literalSubsegment = subsegment as LiteralSubsegment; if (literalSubsegment != null) { // If it's a literal we hold on to it until we are sure we need to add it pendingPartsAreAllSafe = true; pendingParts.Append(UrlEncode(literalSubsegment.Literal)); } else { ParameterSubsegment parameterSubsegment = subsegment as ParameterSubsegment; if (parameterSubsegment != null) { if (pendingPartsAreAllSafe) { // Accept if (pendingParts.Length > 0) { if (blockAllUrlAppends) { return(null); } // Append any pending literals to the URL url.Append(pendingParts.ToString()); pendingParts.Length = 0; addedAnySubsegments = true; } } pendingPartsAreAllSafe = false; // If it's a parameter, get its value object acceptedParameterValue; bool hasAcceptedParameterValue = acceptedValues.TryGetValue(parameterSubsegment.ParameterName, out acceptedParameterValue); if (hasAcceptedParameterValue) { unusedNewValues.Remove(parameterSubsegment.ParameterName); } object defaultParameterValue; defaultValues.TryGetValue(parameterSubsegment.ParameterName, out defaultParameterValue); if (RoutePartsEqual(acceptedParameterValue, defaultParameterValue)) { // If the accepted value is the same as the default value, mark it as pending since // we won't necessarily add it to the URL we generate. pendingParts.Append(UrlEncode(Convert.ToString(acceptedParameterValue, CultureInfo.InvariantCulture))); } else { if (blockAllUrlAppends) { return(null); } // Add the new part to the URL as well as any pending parts if (pendingParts.Length > 0) { // Append any pending literals to the URL url.Append(pendingParts.ToString()); pendingParts.Length = 0; } url.Append(UrlEncode(Convert.ToString(acceptedParameterValue, CultureInfo.InvariantCulture))); addedAnySubsegments = true; } } else { Debug.Fail("Invalid path subsegment type"); } } } if (addedAnySubsegments) { // See comment above about why we add the pending parts if (pendingParts.Length > 0) { if (blockAllUrlAppends) { return(null); } // Append any pending literals to the URL url.Append(pendingParts.ToString()); pendingParts.Length = 0; } } } else { Debug.Fail("Invalid path segment type"); } } } if (pendingPartsAreAllSafe) { // Accept if (pendingParts.Length > 0) { if (blockAllUrlAppends) { return(null); } // Append any pending literals to the URL url.Append(pendingParts.ToString()); } } // Process constraints keys if (constraints != null) { // If there are any constraints, mark all the keys as being used so that we don't // generate query string items for custom constraints that don't appear as parameters // in the URL format. foreach (var constraintsItem in constraints) { unusedNewValues.Remove(constraintsItem.Key); } } // Add remaining new values as query string parameters to the URL if (unusedNewValues.Count > 0) { // Generate the query string bool firstParam = true; foreach (string unusedNewValue in unusedNewValues) { object value; if (acceptedValues.TryGetValue(unusedNewValue, out value)) { url.Append(firstParam ? '?' : '&'); firstParam = false; url.Append(Uri.EscapeDataString(unusedNewValue)); url.Append('='); url.Append(Uri.EscapeDataString(Convert.ToString(value, CultureInfo.InvariantCulture))); } } } return(new BoundUrl { Url = url.ToString(), Values = acceptedValues }); }
private bool ProcessConstraintInternal(HttpContextBase httpContext, Route route, object constraint, string parameterName, RouteValueDictionary values, RouteDirection routeDirection, RequestContext reqContext, out bool invalidConstraint) { invalidConstraint = false; IRouteConstraint irc = constraint as IRouteConstraint; if (irc != null) { return(irc.Match(httpContext, route, parameterName, values, routeDirection)); } string s = constraint as string; if (s != null) { string v = null; object o; // NOTE: If constraint was not an IRouteConstraint, is is asumed // to be an object 'convertible' to string, or at least this is how // ASP.NET seems to work by the tests i've done latelly. (pruiz) if (values != null && values.TryGetValue(parameterName, out o)) { v = Convert.ToString(o, CultureInfo.InvariantCulture); } if (!String.IsNullOrEmpty(v)) { return(MatchConstraintRegex(v, s)); } #if NET_4_0 else if (reqContext != null) { RouteData rd = reqContext != null ? reqContext.RouteData : null; RouteValueDictionary rdValues = rd != null ? rd.Values : null; if (rdValues == null || rdValues.Count == 0) { return(false); } if (!rdValues.TryGetValue(parameterName, out o)) { return(false); } v = Convert.ToString(o, CultureInfo.InvariantCulture); if (String.IsNullOrEmpty(v)) { return(false); } return(MatchConstraintRegex(v, s)); } #endif return(false); } invalidConstraint = true; return(false); }
private bool ProcessConstraintInternal(HttpContextBase httpContext, Route route, object constraint, string parameterName, RouteValueDictionary values, RouteDirection routeDirection, RequestContext reqContext, out bool invalidConstraint) { invalidConstraint = false; IRouteConstraint irc = constraint as IRouteConstraint; if (irc != null) { return(irc.Match(httpContext, route, parameterName, values, routeDirection)); } string s = constraint as string; if (s != null) { string v; object o; if (values != null && values.TryGetValue(parameterName, out o)) { v = o as string; } else { v = null; } if (!String.IsNullOrEmpty(v)) { return(MatchConstraintRegex(v, s)); } #if NET_4_0 else if (reqContext != null) { RouteData rd = reqContext != null ? reqContext.RouteData : null; RouteValueDictionary rdValues = rd != null ? rd.Values : null; if (rdValues == null || rdValues.Count == 0) { return(false); } if (!rdValues.TryGetValue(parameterName, out o)) { return(false); } v = o as string; if (String.IsNullOrEmpty(v)) { return(false); } return(MatchConstraintRegex(v, s)); } #endif return(false); } invalidConstraint = true; return(false); }