C#之 UrlEncode

来源:互联网 发布:usa123456新域名 编辑:程序博客网 时间:2024/05/09 23:37

问题是因为在引入上传数据加密后出现的。

(原文链接 http://ddbiz.com/?p=221)

之前的代码段:

    客户端:

                ......

                string rurl = RemoteHost + "/xxx/XXX/ImpX";

                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(rurl);
                webRequest.CookieContainer = RemoteRequest.RequestCookies;
                webRequest.Accept = "*/*";
                webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)";
                webRequest.AllowAutoRedirect = false;
                webRequest.ServicePoint.Expect100Continue = false;
                webRequest.Method = "POST";
                webRequest.ContentType = "application/x-www-form-urlencoded";
                webRequest.Credentials = CredentialCache.DefaultCredentials;

                StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream());
                requestWriter.Write( postData );
                requestWriter.Close();

                HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    Stream sr = response.GetResponseStream();
                    byte[] br = new byte[response.ContentLength];
                    sr.Read(br, 0, (int)response.ContentLength);
                    sr.Close();
                }

                ......

    服务端:

                 ......

                string v = context.Request.Form["Id"];
                ......

客户端默认的组织参数形式如

    postData = string.Formt("A={0}&B={1}&C={2}", a, b, c);

都可以在服务端正确的被解析,而未做特别控制。但是如果我对postData进行数据加密后(结果采用Base64编码),问题就出现了, 服务端解析出来的变量,会把 '+'  转译回 ' ',这样造成了无法还原Base64到加密结果集。'+' 本来就是 Base64 的组成部分。被替换后当然无法还原。

    webRequest.ContentType = "application/x-www-form-urlencoded";
是 webRequest 在提交数据的时候自动编码还是需要手动编码?从我遇到的这个情况看,需要手动编码 name=value 的 value 数据: name=HttpUtility.UrlEncode(value);且服务端可以直接使用 Request.Form["name"]来取得 value 的原值并不需要再调用 HttpUtility.UrlDecode(value);

(原文链接 http://ddbiz.com/?p=221)