0

我有一个名称值集合,它被传递到通过 Web 客户端发送到另一个系统的方法中。

public string DoExtendedTransferAsString(string operation, NameValueCollection query, FormatCollection formats)
{
    System.Net.WebClient client = new System.Net.WebClient();
    client.QueryString = query;
    client.QueryString["op"] = operation;
    client.QueryString["session"] = SessionId;
    using (Stream stream = client.OpenRead(url))
    {
        FormatCollection formats = new FormatCollection(stream);
    }
    return formats;
}

我需要对 NameValueCollection 中的所有值运行 HttpUtility.HtmlEncode,但我不确定如何操作。注意我无法更改调用代码,因此它必须是 NameValueCollection。

谢谢

4

3 回答 3

3

试试这个

myCollection.AllKeys
    .ToList()
    .ForEach(k => myCollection[k] = 
            HttpUtility.HtmlEncode(myCollection[k]));
于 2010-12-03T14:10:58.080 回答
0

来自 MSDN:

class MyNewClass
   {
      public static void Main()
      {
         String myString;
         Console.WriteLine("Enter a string having '&' or '\"'  in it: ");
         myString=Console.ReadLine();
         String myEncodedString;
         // Encode the string.
         myEncodedString = HttpUtility.HtmlEncode(myString);
         Console.WriteLine("HTML Encoded string is "+myEncodedString);
         StringWriter myWriter = new StringWriter();
         // Decode the encoded string.
         HttpUtility.HtmlDecode(myEncodedString, myWriter);
         Console.Write("Decoded string of the above encoded string is "+
                        myWriter.ToString());
      }
   }

您在 for/foreach 循环中为集合中的每个值执行编码部分。

如果这不是您想要的,请在问题中更加明确。

于 2010-12-03T13:48:38.877 回答
0

我认为这将完成您想要的...

    public string DoExtendedTransferAsString(string operation, NameValueCollection query, FormatCollection formats)
    {
        foreach (string key in query.Keys)
        {
            query[key] = HttpUtility.HtmlEncode(query[key]);
        }

        System.Net.WebClient client = new System.Net.WebClient();
        client.QueryString = query;
        client.QueryString["op"] = operation;
        client.QueryString["session"] = SessionId;
        using (Stream stream = client.OpenRead(url))
        {
            FormatCollection formats = new FormatCollection(stream);
        }
        return formats;
    }

请注意我在其中添加的 foreach,您只是在遍历所有键,使用键获取每个项目并在其上调用 HtmlEncode 并将其放回原处。

于 2010-12-03T13:59:46.083 回答