How to use C# encode and decode 'Chinese'

2019-07-04 15:57发布

In my ASP.NET MVC application i am using Chinese Category Name, it was displayed as %E8%82%B2%E5%84%BF in IE's URL address, but the actual value is '育儿'.

I want to know how can I convert '育儿' into %E8%82%B2%E5%84%BF in C# and how can I convert it back, too. Is it possible display '育儿' in the URL link directly? Will it be good for SEO?

3条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-07-04 16:24

Did you check to make sure that you are using the Unicode encoding (instead of the Default)? Default encoding will not handle Chinese characters.

查看更多
萌系小妹纸
3楼-- · 2019-07-04 16:27

The text displayed in IE's address bar is the URL encoded form of the hex version of those characters. The hex version of '育儿' encoded in UTF-8 is E882B2E584BF:

byte[] buffer = new byte[] { 0xE8, 0x82, 0xB2, 0xE5, 0x84, 0xBF };
string s = Encoding.UTF8.GetString(buffer);

s is equal to '育儿'.

You shouldn't transmit the straight chinese characters in the URL, it should be URL encoded using HttpServerUtility.UrlEncode and UrlDecode.

查看更多
Evening l夕情丶
4楼-- · 2019-07-04 16:37

HttpUtility.UrlEncode will encode a URL, and HttpUtility.UrlDecode will change it back.

Example:

string orig = "http://example.com/育儿";
string encoded = HttpUtility.UrlEncode(orig);
// encoded should equal "http://example.com/%E8%82%B2%E5%84%BF"
查看更多
登录 后发表回答