Created
January 16, 2015 17:38
-
-
Save ScottIsAFool/8ae9da0632d711ff9606 to your computer and use it in GitHub Desktop.
UriExtension returning IDictionary<string, string>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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