Skip to content

Instantly share code, notes, and snippets.

@ScottIsAFool
Created January 16, 2015 17:38
Show Gist options
  • Save ScottIsAFool/8ae9da0632d711ff9606 to your computer and use it in GitHub Desktop.
Save ScottIsAFool/8ae9da0632d711ff9606 to your computer and use it in GitHub Desktop.
UriExtension returning IDictionary<string, string>
public static class UriExtensions
{
/// <summary>
/// Gets a collection of query string values.
/// </summary>
/// <param name="uri">The current uri.</param>
/// <returns>A collection that contains the query string values.</returns>
public static IDictionary<string, string> QueryString(this Uri uri)
{
var uriString = uri.IsAbsoluteUri ? uri.AbsoluteUri : uri.OriginalString;
var queryIndex = uriString.IndexOf("?", StringComparison.OrdinalIgnoreCase);
if (queryIndex == -1)
{
return new Dictionary<string, string>();
}
var query = uriString.Substring(queryIndex + 1);
return query.Split('&')
.Where(x => !string.IsNullOrEmpty(x))
.Select(x => x.Split('='))
.ToDictionary(x => WebUtility.UrlDecode(x[0]), x=> x.Length == 2 && !string.IsNullOrEmpty(x[1]) ? WebUtility.UrlDecode(x[1]) : null);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment