Url Unicode characters encoding

2019-04-30 18:05发布

问题:

How to encode URLs containing Unicode? I would like to pass it to a command line utility and I need to encode it first.

Example: http://zh.wikipedia.org/wiki/白雜訊

becomes http://zh.wikipedia.org/wiki/%E7%99%BD%E9%9B%9C%E8%A8%8A.

回答1:

You can use the HttpUtility.UrlPathEncode method in the System.Web assembly (requires the full .NET Framework 4 profile):

var encoded = HttpUtility.UrlPathEncode("http://zh.wikipedia.org/wiki/白雜訊");


回答2:

According to MSDN you can't use UrlPathEncode anymore.

So, Correct way of doing it now is,

var urlString = Uri.EscapeUriString("http://zh.wikipedia.org/wiki/白雜訊");


回答3:

I had Turkish character problem.<a href="/@Html.Raw(string)" solved the problem



回答4:

Server.UrlEncode(s);

.NET strings are natively Unicode strings (UTF-8 encoded, to be specific) so you need to nothing more than invoke HttpServerUtility.UrlEncode (though the so-called "intrinsic" Server property will be available in most contexts in asp.net where you may want to do this).