Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# HttpWebReqest - escape POST content?

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?

like image 574
Andrew Ensley Avatar asked Apr 20 '09 22:04

Andrew Ensley


3 Answers

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

like image 180
Paul Alexander Avatar answered Sep 28 '22 21:09

Paul Alexander


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.

like image 40
Andrew Ensley Avatar answered Sep 28 '22 21:09

Andrew Ensley


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

like image 33
Glen Tankersley Avatar answered Sep 28 '22 19:09

Glen Tankersley