Tutorial :C# HttpWebReqest - escape POST content?



Question:

When I've uploaded content from my C# app to a website in the past, I've used a POST request like so:

    HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://" + this.server + "/log.php");      wr.Method = "POST";      wr.ContentType = "application/x-www-form-urlencoded";      string paramString = "v=" + this.version + "&m=" + this.message;      wr.ContentLength = paramString.Length;      StreamWriter stOut = new StreamWriter(wr.GetRequestStream(), System.Text.Encoding.ASCII);      stOut.Write(paramString);      stOut.Close();  

My problem is that now I'm in a situation where this.message will very likely contain newlines, tabs, and special characters including "&" and "=". Do I need to escape this content. If so, how?


Solution:1

You can use HttpUtility.HtmlEncode/HtmlDecode or UrlEncode/UrlDecode as appropriate.


Solution:2

Just for reference, the solution to my problem was in:

System.Web.HttpUtility.UrlEncode

Which is supported by all versions of the .Net framework =p

Specifically, I'm using the overload that takes a string as an argument. Running this on all parameter values will make them safe for POSTing.


Solution:3

System.Web is outdated - use System.Net.WebUtility instead...


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »