本文整理汇总了C#中System.Collections.Specialized.NameValueCollection.Cast方法的典型用法代码示例。如果您正苦于以下问题:C# NameValueCollection.Cast方法的具体用法?C# NameValueCollection.Cast怎么用?C# NameValueCollection.Cast使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Collections.Specialized.NameValueCollection
的用法示例。
在下文中一共展示了NameValueCollection.Cast方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: IsAuthenticRequest
/// <summary>
/// Determines if an incoming request is authentic.
/// </summary>
/// <param name="querystring">The collection of querystring parameters from the request. Hint: use Request.QueryString if you're calling this from an ASP.NET MVC controller.</param>
/// <param name="shopifySecretKey">Your app's secret key.</param>
/// <returns>A boolean indicating whether the request is authentic or not.</returns>
public static bool IsAuthenticRequest(NameValueCollection querystring, string shopifySecretKey)
{
string signature = querystring.Get("signature");
//Convert the querystring to a dictionary, which lets us query it with LINQ
IDictionary<string, string> parameters = querystring
.Cast<string>()
.Select(s => new { Key = s, Value = querystring[s] })
.ToDictionary(d => d.Key, d => d.Value);
//To calculate signature, order all querystring parameters by alphabetical (exclude the signature itself), and append it to the secret key.
string calculatedSignature = shopifySecretKey + string.Join(null, parameters
.Where(x => x.Key != "signature")
.OrderBy(x => x.Key)
.Select(x => string.Format("{0}={1}", x.Key, x.Value)));
//Convert calculated signature to bytes
Byte[] sigBytes = Encoding.UTF8.GetBytes(calculatedSignature);
//Runt hose bytes through an MD5 hash
using (MD5 md5 = MD5.Create())
{
sigBytes = md5.ComputeHash(sigBytes);
}
//Convert bytes back to string, replacing dashes, to get the final signature.
calculatedSignature = BitConverter.ToString(sigBytes).Replace("-", "");
//Request is valid if the calculated signature matches the signature from the querystring.
return calculatedSignature.ToUpper() == signature.ToUpper();
}
示例2: Create
public FlowRequest Create(NameValueCollection nameValueCollection)
{
Dictionary<string, string> dictionary = nameValueCollection.Cast<string>()
.Select(s => new {Key = s, Value = nameValueCollection[s]})
.ToDictionary(p => p.Key, p => p.Value);
return Create(dictionary);
}
示例3: QueryBuilder
public QueryBuilder(NameValueCollection collection)
{
Query = collection == null ?
string.Empty :
string.Join(AMPERSAND,
collection.Cast<string>()
.Where(key => !string.IsNullOrEmpty(key))
.Select(key => encode(key)+ EQUALS + encode(collection[key])));
}
示例4: Parse
public void Parse(NameValueCollection nameValueCollection)
{
if (nameValueCollection != null)
{
_settings = nameValueCollection.Cast<NameObjectCollectionBase>().Select(nvc => new Setting
{
Key =nvc.
});
return _settings;
}
}
示例5: SerializeRequestToBytes
public static byte[] SerializeRequestToBytes(this HttpRequestBase request, string renameHost)
{
if (string.IsNullOrEmpty(renameHost))
return SerializeRequestToBytes(request);
return SerializeRequestToBytes(request, r => {
var requestHeaders = new NameValueCollection(r.Headers);
requestHeaders["Host"] = renameHost;
var headers = requestHeaders.Cast<string>()
.Select(h => string.Format("{0}: {1}", h, r.Headers[h]))
.ToArray();
return string.Join(Environment.NewLine, headers);
});
}
示例6: ConstructStringToSign
public static string ConstructStringToSign(string httpMethod, NameValueCollection headers, string pathAndQuery)
{
StringBuilder stringToSign = new StringBuilder();
var httpVerb = httpMethod.Trim() + "\n";
var csodHeaders = headers.Cast<string>().Where(w => w.StartsWith("x-csod-"))
.Where(w => w != "x-csod-signature")
.Distinct()
.OrderBy(s => s)
.Aggregate(string.Empty, (a, l) => a + l.ToLower().Trim() + ":" + headers[l].Trim() + "\n");
stringToSign.Append(httpVerb);
stringToSign.Append(csodHeaders);
stringToSign.Append(pathAndQuery);
return stringToSign.ToString();
}
示例7: IsAuthenticRequest
/// <summary>
/// Determines if an incoming request is authentic.
/// </summary>
/// <param name="querystring">The collection of querystring parameters from the request. Hint: use Request.QueryString if you're calling this from an ASP.NET MVC controller.</param>
/// <param name="shopifySecretKey">Your app's secret key.</param>
/// <returns>A boolean indicating whether the request is authentic or not.</returns>
public static bool IsAuthenticRequest(NameValueCollection querystring, string shopifySecretKey)
{
string hmac = querystring.Get("hmac");
if (string.IsNullOrEmpty(hmac))
{
return false;
}
// To calculate HMAC signature:
// 1. Cast querystring to KVP pairs.
// 2. Remove `signature` and `hmac` keys.
// 3. Replace & with %26, % with %25 in keys and values.
// 4. Replace = with %3D in keys only.
// 5. Join each key and value with = (key=value).
// 6. Sorty kvps alphabetically.
// 7. Join kvps together with & (key=value&key=value&key=value).
// 8. Compute the kvps with an HMAC-SHA256 using the secret key.
// 9. Request is authentic if the computed string equals the `hash` in query string.
// Reference: https://docs.shopify.com/api/guides/authentication/oauth#making-authenticated-requests
Func<string, bool, string> replaceChars = (string s, bool isKey) =>
{
//Important: Replace % before replacing &. Else second replace will replace those %25s.
string output = (s?.Replace("%", "%25").Replace("&", "%26")) ?? "";
if (isKey)
{
output = output.Replace("=", "%3D");
}
return output;
};
var kvps = querystring.Cast<string>()
.Select(s => new { Key = replaceChars(s, true), Value = replaceChars(querystring[s], false) })
.Where(kvp => kvp.Key != "signature" && kvp.Key != "hmac")
.OrderBy(kvp => kvp.Key)
.Select(kvp => $"{kvp.Key}={kvp.Value}");
var hmacHasher = new HMACSHA256(Encoding.UTF8.GetBytes(shopifySecretKey));
var hash = hmacHasher.ComputeHash(Encoding.UTF8.GetBytes(string.Join("&", kvps)));
//Convert bytes back to string, replacing dashes, to get the final signature.
var calculatedSignature = BitConverter.ToString(hash).Replace("-", "");
//Request is valid if the calculated signature matches the signature from the querystring.
return calculatedSignature.ToUpper() == hmac.ToUpper();
}
示例8: IsAuthenticProxyRequest
/// <summary>
/// Determines if an incoming proxy page request is authentic. Conceptually similar to <see cref="IsAuthenticRequest(NameValueCollection, string)"/>,
/// except that proxy requests use HMACSHA256 rather than MD5.
/// </summary>
/// <param name="querystring">The collection of querystring parameters from the request. Hint: use Request.QueryString if you're calling this from an ASP.NET MVC controller.</param>
/// <param name="shopifySecretKey">Your app's secret key.</param>
/// <returns>A boolean indicating whether the request is authentic or not.</returns>
public static bool IsAuthenticProxyRequest(NameValueCollection querystring, string shopifySecretKey)
{
string signature = querystring.Get("signature");
// To calculate signature, order all querystring parameters by alphabetical (exclude the
// signature itself). Then, hash it with the secret key.
var parameters = querystring
.Cast<string>()
.Select(s => new { Key = s, Value = querystring[s] })
.ToDictionary(d => d.Key, d => d.Value)
.Where(x => x.Key != "signature")
.OrderBy(x => x.Key)
.Select(x => string.Format("{0}={1}", x.Key, x.Value));
var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(shopifySecretKey));
var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(string.Join(null, parameters)));
//Convert bytes back to string, replacing dashes, to get the final signature.
var calculatedSignature = BitConverter.ToString(hash).Replace("-", "");
//Request is valid if the calculated signature matches the signature from the querystring.
return calculatedSignature.ToUpper() == signature.ToUpper();
}
示例9: Dump
public static string Dump(NameValueCollection nameValueCollection)
{
return nameValueCollection.Cast<string>().ToString(key => key + ": " + nameValueCollection[key], "\r\n");
}
示例10: GetSignatureHash
private String GetSignatureHash(NameValueCollection col)
{
return GetSignatureHash(col.Cast<string>().Select(e => col[e]));
}
示例11: BuildDictionaryFromNameValueCollection
private static Dictionary<string, string> BuildDictionaryFromNameValueCollection( NameValueCollection nameValueCollection )
{
return nameValueCollection.Cast<string>().Select( s => new
{
Key = s,
Value = nameValueCollection[s]
} ).ToDictionary( p => p.Key, p => p.Value );
}
示例12: Page_Load
protected void Page_Load(object sender, EventArgs e)
{
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback((a, b, c, d) => true);
// Create a request using a URL that can receive a post.
//WebRequest request = WebRequest.Create("https://localhost:44300/login");
//RESTSHARP!
var restclient = new RestClient("https://localhost:44300");
restclient.Authenticator = new SimpleAuthenticator("userName", "mathieu", "password", "asd");
var restrequest = new RestRequest("/login", Method.POST);
restrequest.AddHeader("Accept", "*/*");
var restresponse = restclient.Execute(restrequest);
var responseCookies = restresponse.Cookies;
restclient.AddDefaultHeader("Client", "RichClient");
restclient.Authenticator = null;
var secureRequest = new RestRequest("/secure");
//secureRequest.AddCookie(responseCookies[0].Name, responseCookies[0].Value);
var secureResponse = restclient.Execute(secureRequest);
CookieContainer cookieJar = new CookieContainer();
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://localhost:44300/login");
request.CookieContainer = cookieJar;
request.Headers.Add("Client", "RichClient");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
NameValueCollection nvc = new NameValueCollection();
nvc.Add("userName", "mathieu");
nvc.Add("password", "abc");
var values = nvc.Cast<string>().Select(x => string.Format("{0}={1}", x, HttpUtility.UrlEncode(nvc[x]))).ToArray();
var postValues = string.Join("&", values);
byte[] byteArray = Encoding.UTF8.GetBytes(postValues);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
//WebResponse response = request.GetResponse();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
int cookieCount = cookieJar.Count;
var cookies = cookieJar.GetCookies(new Uri("http://localhost"));
var cookieValue = cookies.Cast<Cookie>().First().Value;
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
OtherRequest(cookieJar);
}
示例13: CreateErrorResult
protected Exception CreateErrorResult(NameValueCollection errors)
{
return new Exception(errors.Cast<string>().Select(e => errors[e]).ToString());
}
示例14: Submit
private NameValueCollection Submit(NameValueCollection values,string requestUrl)
{
string data = String.Join("&", values.Cast<string>()
.Select(key => String.Format("{0}={1}", key, HttpUtility.UrlEncode(values[key]))));
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl);
request.Method = "POST";
request.ContentLength = data.Length;
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(data);
}
using (StreamReader reader = new StreamReader(request.GetResponse().GetResponseStream()))
{
return HttpUtility.ParseQueryString(reader.ReadToEnd());
}
}
示例15: GetUrl
private string GetUrl(NameValueCollection values, string requestUrl)
{
string data = String.Join("&", values.Cast<string>()
.Select(key => String.Format("{0}={1}", key, HttpUtility.UrlEncode(values[key]))));
return String.Format("{0}/{1}", requestUrl, data);
}