Created
September 29, 2014 00:03
-
-
Save pedrolamas/1d02acc76c8fdad77f99 to your computer and use it in GitHub Desktop.
UriExtensions class used in Cimbalino Toolkit with some changes to show the usage of optional parameters
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
// **************************************************************************** | |
// <copyright file="UriExtensions.cs" company="Pedro Lamas"> | |
// Copyright © Pedro Lamas 2014 | |
// </copyright> | |
// **************************************************************************** | |
// <author>Pedro Lamas</author> | |
// <email>[email protected]</email> | |
// <project>Cimbalino.Toolkit.Core</project> | |
// <web>http://www.pedrolamas.com</web> | |
// <license> | |
// See license.txt in this solution or http://www.pedrolamas.com/license_MIT.txt | |
// </license> | |
// **************************************************************************** | |
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Net; | |
namespace Cimbalino.Toolkit.Extensions | |
{ | |
/// <summary> | |
/// Provides a set of static (Shared in Visual Basic) methods for <see cref="Uri"/> instances. | |
/// </summary> | |
public static class UriExtensions | |
{ | |
/// <summary> | |
/// Gets a collection of query string values. | |
/// </summary> | |
/// <param name="uri">The current uri.</param> | |
/// <param name="includeEmptyValues">Include empty values in result.</param> | |
/// <returns>A collection that contains the query string values.</returns> | |
public static IEnumerable<KeyValuePair<string, string>> QueryString(this Uri uri, bool includeEmptyValues = true) | |
{ | |
var uriString = uri.IsAbsoluteUri ? uri.AbsoluteUri : uri.OriginalString; | |
var queryIndex = uriString.IndexOf("?", StringComparison.OrdinalIgnoreCase); | |
if (queryIndex == -1) | |
{ | |
return Enumerable.Empty<KeyValuePair<string, string>>(); | |
} | |
var query = uriString.Substring(queryIndex + 1); | |
return query.Split('&') | |
.Where(x => !string.IsNullOrEmpty(x)) | |
.Select(x => (x + "=").Split('=')) | |
.Where(x => includeEmptyValues || !string.IsNullOrEmpty(x[1])) | |
.Select(x => new KeyValuePair<string, string>(WebUtility.UrlDecode(x[0]), WebUtility.UrlDecode(x[1]))); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment