How to use C# encode and decode 'Chinese' characters

梦想的初衷 提交于 2019-12-23 18:44:42

问题


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?


回答1:


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.




回答2:


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"



回答3:


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



来源:https://stackoverflow.com/questions/1375257/how-to-use-c-sharp-encode-and-decode-chinese-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!