ASP.net / c#将NameValueCollection转换为字典

本文关键字:转换 字典 NameValueCollection net ASP | 更新日期: 2023-09-27 18:10:42

我正在帮我儿子升级我去年为他建的网站。他想要实现Amazon Simple Pay。我是如此接近得到它,但有一个错误,我不知道如何解决。这是ASP。。Net网站用c#完成。我是一个未经训练(自学成才)的开发人员,所以请简单地说。: -)

在ASP。Net,它是不合法的有一个表单内的表单,我需要做一个表单POST。网上有一个相当漂亮的教程,展示了如何做到这一点。如果你有兴趣的话,网址是http://weblogs.asp.net/hajan/archive/2011/04/20/amazon-simple-pay-in-asp-net.aspx。

事务必须被"签名",Amazon提供了一个SignatureUtils类来完成此操作。在那个类中,我调用这个:

public static string signParameters(IDictionary<String, String> parameters, String key, String HttpMethod, String Host, String RequestURI, String algorithm) 

让我抓狂的是字典参数。我要传递给它的是这个ListParams NameValueCollection我用:

public System.Collections.Specialized.NameValueCollection ListParams = new System.Collections.Specialized.NameValueCollection();

它给了我下面的错误,因为它不能将NameValueCollection转换为字典。我试图明确地转换它,但没有乐趣。我怎么解决这个问题?

Error: Argument 1: cannot convert from 'System.Collections.Specialized.NameValueCollection' to 'System.Collections.Generic.IDictionary<string,string>'

ASP.net / c#将NameValueCollection转换为字典

您可以使用Cast:

IDictionary<string, string> dict = ListParams.Cast<string>()
    .ToDictionary(p => p, p => ListParams[p]);

您还可以通过AllKeys属性将NameValueCollection"转换"为Dictionary<string, string>:

var dictionary = nameValueCollection.AllKeys
    .ToDictionary(k => k, k => nameValueCollection[k]);

赞!!得到它!解决方案是更改Hajan提供的示例代码,以实现Dictionary而不是NameValueCollection。然后我需要将PaymentGatewayPost中的while循环更改为foreach循环,如下所示:

foreach (KeyValuePair<string, string> pair in ListParams)
{
    System.Web.HttpContext.Current.Response.Write(string.Format("<input name='"{0}'" type='"hidden'" value='"{1}'">",
    pair.Key,
    pair.Value));
}

瞧! !

谢谢大家的帮助。希望这能帮助到那些还在为Amazon Simple Pay而挣扎的人。