Let's take a look at the following two URLs, do they pass the same parameters? aaa.aspx?tag=.net%bc%bc%ca%f5 aaa.aspx?tag=.net%e6%8a%80%e6%9c%af
It seems to be different, but in fact, they all use UrlEncode for ".net technology", but one is GB2312 encoding and the other is Utf-8 encoding. The following code can obtain the above encoding effect:
string tmp1 = System.Web.HttpUtility.UrlEncode(".net technology", System.Text.Encoding.GetEncoding("GB2312")); string tmp2 = System.Web.HttpUtility.UrlEncode(".net technology", System.Text.Encoding.UTF8);
Our actual web pages may be called by other programs. For example, Chinese Simplified an ASP page on the operating system needs to pass a Chinese parameter to a ASP.net page. By default, on Chinese Simplified operating systems, ASP's Server.UrlEncode method will encode Chinese with GB2312 encoding. But by default, ASP.net pages are encoded in UTF-8. In this case, when you use Request.QueryString["Tag"] to accept the value, you will not be able to accept Chinese information, and you will see garbled characters in step-by-step debugging. At this time, although Request.QueryString["Tag"] is accepted with garbled characters, the URL at this time is not garbled.
The solution is to analyze the parameters in the URL by yourself, and then decrypt the values of the parameters according to the encoding of GB2312, instead of using the default UTF-8 encoding of .net. In fact, Microsoft similarly provides corresponding functions, so we don't have to use regular expressions to analyze URL strings ourselves.
The demo code is as follows:
string q = Request.Url.Query;
System.Collections.Specialized.NameValueCollection nv = System.Web.HttpUtility.ParseQueryString(q, System.Text.Encoding.GetEncoding("GB2312")); Response.Write(nv["Tag"]);
Let's use Lutz Roeder's .NET Reflector to look at the implementation of the System.Web.HttpUtility.ParseQueryString method: If we keep checking back, we can see that the code that finally handles the URL parameter string analysis is as follows:
The following function of the System.Web.HttpValueCollection class implements the parsing of the URL parameter Here we see that it is an analysis carried out by each character.
As for what kind of encoding method the other party passes to us, it is best to pass it as a parameter, so that we can decrypt it according to this parameter of the user. |