当前位置: 首页>>代码示例>>C#>>正文


C# NameValueCollection.Cast方法代码示例

本文整理汇总了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();
        }
开发者ID:mooglegiant,项目名称:ShopifySharp,代码行数:37,代码来源:ShopifyAuthorizationService.cs

示例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);
        }
开发者ID:pekkah,项目名称:Tanka.FileSystem.WebApi,代码行数:8,代码来源:FlowRequestReader.cs

示例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])));
 }
开发者ID:dgg,项目名称:testing-commons,代码行数:9,代码来源:QueryBuilder.cs

示例4: Parse

        public void Parse(NameValueCollection nameValueCollection)
        {
            if (nameValueCollection != null)
            {
                _settings = nameValueCollection.Cast<NameObjectCollectionBase>().Select(nvc => new Setting
                {
                    Key =nvc.
                });

                return _settings;
            }
        }
开发者ID:Gotik88,项目名称:DRBlog,代码行数:12,代码来源:WebConfigSectionParser.cs

示例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);
     });
 }
开发者ID:mausch,项目名称:ElmahFiddler,代码行数:13,代码来源:HttpRequestExtensions.cs

示例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();
 }
开发者ID:cornerstoneondemand,项目名称:CSOD-Sample-Service-Call-POST,代码行数:14,代码来源:Program.cs

示例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();
        }
开发者ID:nozzlegear,项目名称:ShopifySharp,代码行数:55,代码来源:ShopifyAuthorizationService.cs

示例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();
        }
开发者ID:mooglegiant,项目名称:ShopifySharp,代码行数:30,代码来源:ShopifyAuthorizationService.cs

示例9: Dump

 public static string Dump(NameValueCollection nameValueCollection)
 {
     return nameValueCollection.Cast<string>().ToString(key => key + ": " + nameValueCollection[key], "\r\n");
 }
开发者ID:nuub666,项目名称:framework,代码行数:4,代码来源:Exception.cs

示例10: GetSignatureHash

 private String GetSignatureHash(NameValueCollection col)
 {
     return GetSignatureHash(col.Cast<string>().Select(e => col[e]));
 }
开发者ID:sailthru,项目名称:sailthru-net-client,代码行数:4,代码来源:SailthruClient.cs

示例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 );
 }
开发者ID:rjmporter,项目名称:GetHash,代码行数:8,代码来源:CryptoToken.cs

示例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);
        }
开发者ID:BredStik,项目名称:NancyInWebApp,代码行数:76,代码来源:Default.aspx.cs

示例13: CreateErrorResult

 protected Exception CreateErrorResult(NameValueCollection errors)
 {
     return new Exception(errors.Cast<string>().Select(e => errors[e]).ToString());
 }
开发者ID:chrisdaaaaay,项目名称:Merchello.Plugins.SagePay,代码行数:4,代码来源:SagePayPaymentProcessorBase.cs

示例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());
            }
        }
开发者ID:vietplayfuri,项目名称:Asp_Master,代码行数:19,代码来源:PayPal.cs

示例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);
 }
开发者ID:vietplayfuri,项目名称:Asp_Master,代码行数:6,代码来源:PayPal.cs


注:本文中的System.Collections.Specialized.NameValueCollection.Cast方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。