在NameValueCollection C#.net中编码值

时间:2010-12-03 13:40:40

标签: c# .net namevaluecollection

我有一个名称值集合,它被传递到一个方法,通过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。

由于

3 个答案:

答案 0 :(得分:3)

试试这个

myCollection.AllKeys
    .ToList()
    .ForEach(k => myCollection[k] = 
            HttpUtility.HtmlEncode(myCollection[k]));

答案 1 :(得分: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循环中为集合中的每个值执行编码部分。

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

答案 2 :(得分: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并将其放回原位。