using System;
using System.Collections.Generic;
using System.Text;
namespace Unity.Services.Authentication.Utilities
{
static class HttpUtilities
{
///
/// Parse and decode the query string to a dictionary with values decoded.
///
///
/// This function only works when there is a single value per key.
///
/// The query string to parse.
/// The query string decoded.
public static IDictionary ParseQueryString(string queryString)
{
var result = new Dictionary();
var splitQuery = queryString.Split('?', '&');
foreach (var param in splitQuery)
{
var assignmentIndex = param.IndexOf('=');
if (assignmentIndex >= 0)
{
var paramName = UnescapeUrlString(param.Substring(0, assignmentIndex));
var paramValue = UnescapeUrlString(param.Substring(assignmentIndex + 1));
result[paramName] = paramValue;
}
}
return result;
}
///
/// Encode the dictionary to a URL query parameter.
///
///
/// This function only works when there is a single value per key.
///
/// A dictionary that represents the query parameters.
/// The encoded query string without the preceding question mark.
public static string EncodeQueryString(IDictionary queryParams)
{
var result = new StringBuilder();
var firstParam = true;
foreach (var param in queryParams)
{
if (!firstParam)
{
result.Append('&');
}
else
{
firstParam = false;
}
result.Append(EscapeUrlString(param.Key)).Append('=').Append(EscapeUrlString(param.Value));
}
return result.ToString();
}
///
/// Encode any raw string to a URL encoded string that can be placed after =.
///
/// The string to encode. Any special character is okay.
/// The URL encoded string.
static string EscapeUrlString(string rawString)
{
// Don't use Uri.EscapeUriString it has issue encoding reserved characters.
return Uri.EscapeDataString(rawString);
}
///
/// Decode the URL escaped string to a raw URL.
///
/// The url string to decode.
/// The raw string decoded.
static string UnescapeUrlString(string urlString)
{
return Uri.UnescapeDataString(urlString);
}
}
}