C#使用特殊字符发送请求会影响字符串。

4

我从解决方案中的一个项目向另一个项目发送请求:

WebRequest request = WebRequest.Create(UrlTemplate);
request.Timeout = 500000;
request.Method = WebRequestMethods.Http.Post;
request.ContentType = ContentType;
byte[] postData = System.Text.Encoding.ASCII.GetBytes(data);
request.ContentLength = postData.Length;
Stream newStream = request.GetRequestStream();
// Send the data.
newStream.Write(postData, 0, postData.Length);
newStream.Flush();
newStream.Close();

在设置了UrlTemplate的函数中,我得到了正确的字符串(我将其发送到数据中),但问题在于当字符串包含特殊字符时。
如果字符串是:12&34 我在函数中得到的是:12
如果字符串是:12+34 我在函数中得到的是:12 34
我很乐意知道是否有人遇到过这种情况以及如何解决。提前感谢您。

1
请参考以下链接了解URL转义字符的相关内容:http://www.werockyourweb.com/url-escape-characters - Rotem
@ParPar您考虑将一个标记为答案了吗? - Owais Qureshi
3个回答

7

在构建UrlTemplate时,请使用System.Web.HttpUtility.UrlEncode System.Net.WebUtility.UrlEncode


2

抱歉,我刚看到这个信息。现在我明白为什么会发生这种情况了,但是在函数中UrlEncoder却返回了null...还有一件事 - 我需要使用这种发送方式,因为项目中的其他函数也在使用它。难道没有办法强制让特定的字符串保持原样吗? - ParPar
谢谢,我刚才误解了你关于 UrlEncode 的解释...现在我正在使用 HttpUtility.UrlEncode,这完全解决了问题。再次感谢你详细的回答。 - ParPar

1

在您的密码中使用URI.EscapeDataString()方法。它将帮助您正确读取特殊字符。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接