This is one of the (many) utilitarian classes I have that I use with my ASP.NET sites.
The basis of this one is to make gathering certain tokens that I use periodically, to make URL's more friendly.
It's pretty simple, and should be quite obvious. I use it to make URL's a little more friendly. (/Id/SomeKey/SomeValue/OtherKey/OtherValue/
) It returns Id
and creates a dictionary for the remaining pairs of Key
and Value
.
public class RouteUtilities
{
public static Dictionary<string, string> GetRouteKeyValuePairs(RouteValueDictionary dataTokens, int startIndex)
{
Dictionary<string, string> routeItems = new Dictionary<string, string>();
List<string> segments = GetRouteSegments(dataTokens);
for (int i = startIndex; i < segments.Count; i += 2)
{
routeItems.Add(segments[i], segments[i + 1]);
}
return routeItems;
}
public static List<string> GetRouteSegments(RouteValueDictionary dataTokens) => (List<string>)dataTokens["FriendlyUrlSegments"];
public static bool GetIdAndKeys(RouteValueDictionary dataTokens, out int id, out Dictionary<string, string> keys)
{
if (dataTokens.Count > 0)
{
Dictionary<string, string> routeItems = GetRouteKeyValuePairs(dataTokens, 1);
List<string> routeSegments = GetRouteSegments(dataTokens);
if (routeSegments.Count > 0)
{
id = Convert.ToInt32(routeSegments[0]);
keys = GetRouteKeyValuePairs(dataTokens, 1);
return true;
}
}
id = 0;
keys = null;
return false;
}
}