Url for HttpWebRequest truncated by special characters
The URL of a Web Service that I need to call includes a parameter that includes free form text. I'm not sure why it was designed that way since it is sent using POST and includes many fields as part of the POST. But, it is causing me a problem.
For some characters like the pound sign and < >, the URL is truncated when it hits the problem character. I'm HTML encoding the text for the parameter, but the problem remains. I can see special cha开发者_运维问答racters like > are being encoded to something like gt;. I'm thinking that the semicolon in the encoded string is somehow a problem.
I put a sniffer receiving the incoming request at the server and I see there that the URL has been truncated.
At the server I see something like:
...?extraData=kjfkfjslkj
instead of:
...?extraData=kjfkfjslkj#kfjkdlsfj
The code is something like this:
using System.Web;
....
String strExtra="kjfkfjslkj#kfjkdlsfj";
strURL = strStuff + "?extraData=" + System.Web.HttpUtility.HtmlEncode(strExtra);
HttpWebRequest oRequest = (HttpWebRequest)WebRequest.Create(new Uri(strURL));
oRequest.Method = httpMethod;
oRequest.ContentType = "application/atom+xml";
...
using (WebResponse oResponse = oRequest.GetResponse())
{
...
}
Everything after the hash (#
) sign is not sent to the server. It's used by the browser and scripts on the page to denote a location on a page, or some other significance. Remove the hash sign or url encode it (%23
) to send it to the server.
This line:
strURL = strStuff + "?extraData=" + System.Web.HttpUtility.HtmlEncode(strExtra);
should be
strURL = strStuff + "?extraData=" + Server.UrlEncode(strExtra);
encoding for html is useless when using the data in a url.
精彩评论