示例#1
0
        /// <summary>
        /// Generate the route values which could have been mapped by the given route to give access to the (path of the) given data record
        /// </summary>
        /// <param name="route">route in routing table</param>
        /// <param name="data">data record being tested if it could have been accessed via route</param>
        /// <returns>route values that would have mapped to the path of the data record</returns>
        private static RouteValueDictionary GenerateRouteValues(Route route, string path)
        {
            // Get all elements of path from data
            List<string> pathEls = new List<string>();
            if (!string.IsNullOrEmpty(path))
                pathEls = path.Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries).ToList();

            // Get all route values generated by route, with values if they are constant or null if variable
            var allowedVals = route.AllowedValues();

            RouteValueDictionary values = new RouteValueDictionary();
            foreach (var allowedVal in allowedVals)
            {
                int idx = -1;
                if (int.TryParse(allowedVal.Key.UpTo("-"), out idx)) // the route value matches a path element
                {
                    if (idx < 0 || idx >= pathEls.Count)
                        return null;
                    if (allowedVal.Value != null && pathEls[idx] != (string)allowedVal.Value)
                        return null;
                    values.Add(allowedVal.Key, pathEls[idx]);
                }
                else // this should include 'controller' and 'action'
                {
                    if (allowedVal.Value == null)
                        return null;
                    else
                        values.Add(allowedVal.Key, allowedVal.Value);
                }
            }

            if (!(values.ContainsKey("controller") && values.ContainsKey("action")))
                throw new Exception("Content mapping in routing table doesn't specify controller and action, route url = " + route.Url);

            return values;
        }