Today, eggplant _ 2008 reported that the "C ++" label in his blog is invalid. After checking the code, httputility is used to generate the link. URL: httputility is used to obtain tags from the URL. urldecode (URL), from encode to decode, "C ++" is changed to "C" (the plus sign is changed to a space ). This is a well-known problem. Here we will analyze this problem and provide a solution.
Let's take a look at the problem:
1. Original link:
http://www.cnblogs.com/xd502djj/tag/C++/
2. After httputility. urlencode, get:
http://www.cnblogs.com/xd502djj/tag/C%2b%2b/
3. Request. rawurl, and get:
http://www.cnblogs.com/xd502djj/tag/C++/
4. httputility. urldecode, and get:
http://www.cnblogs.com/xd502djj/tag/C /
The above step 3rd has obtained the correct result. The urldecode in step 4th changes the plus sign to a space.
It seems that the solution is very simple. We did the same in the beginning by canceling the urldecode. After a while, some users reported that the "Windows Phone" tag was invalid and changed to "Windows + phone ". We checked that it was originally in httputility. when urlencode is used, the space is converted to the plus sign. You need to call urldecode to restore the plus sign to the space, and then call httputility. urldecode is added (forget the "C ++" label problem ). Then, the "C ++" tag becomes invalid again... in this way, it seems that there are many bugs and work is very busy. It is actually a bug...
Finally one day, we said "We can't do this anymore" and began to look for a solution:
Now that httputility. urlencode () cannot be used, check whether there are any alternatives in. net.
Httputility. urlpathencode () was first found (). Hey, it's useful. It's easy to solve the issue of "C ++" and space, but... Later I found that I couldn't fix "C #" And it didn't encode.
Find URI. escapeuristring (), which is the same as httputility. urlpathencode.
Continue searching... finally found... URI. escapedatastring (), done! See the following test code:
public void UrlEncodeTest()
{
string url = "C++ C#";
Console.WriteLine(HttpUtility.UrlEncode(url));//C%2b%2b+C%23
Console.WriteLine(HttpUtility.UrlPathEncode(url));//C++%20C#
Console.WriteLine(Uri.EscapeUriString(url));//C++%20C#
Console.WriteLine(Uri.EscapeDataString(url));//C%2B%2B%20C%23
}
Note: The runtime environment is. net4.