Encode values in a NameValueCollection C# .net
I have a name value collections which is passed into a method to send to another system via a web client.
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"] = SessionI开发者_如何转开发d;
using (Stream stream = client.OpenRead(url))
{
FormatCollection formats = new FormatCollection(stream);
}
return formats;
}
I need to run HttpUtility.HtmlEncode on all the values inside the NameValueCollection but I am unsure how to. NB I cannot change the calling code so it have to be a NameValueCollection.
Thanks
try this
myCollection.AllKeys
.ToList()
.ForEach(k => myCollection[k] =
HttpUtility.HtmlEncode(myCollection[k]));
From 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());
}
}
You do the encoding part for each value in the collection in a for/foreach loop.
If this is not what you were looking for please be more explicit in the question.
I think this will accomplish what you want...
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;
}
Note the foreach I added in there, you're just iterating through all the keys, grabbing each item using the key and calling HtmlEncode on it and putting it right back.
精彩评论