UrlEncode - Javascript vs C #

I have a url that requires some parameters. The values ​​of these parameters can be accented characters, so I absolutely need UrlEncode them. Oddly enough, I see the difference between the behavior of either Javascript and .NET.

Suppose I try UrlEncode the word "éléphant". In JavaScript (according to this WebSite: http://www.albionresearch.com/misc/urlencode.php ), I get the following:% E9l% E9phant. That seems right to me. However, in .NET with this call (System.Web.HttpUtility.UrlEncode ("éléphant")) I get "% c3% a9l% c3% a9phant". What's wrong? What am I missing? What if I want to get% E9l% E9phant in .NET?

Thanks!

+6
javascript c # encoding urlencode
source share
5 answers

System.Web.HttpUtility.UrlEncode will use UTF8 (I think ..) as its default encoder, you can change this by specifying one of them.

System.Web.HttpUtility.UrlEncode("éléphant", Encoding.Default); // %e9l%e9phant 

Although it may be preferable to specify the actual code page or not, rather than relying on the default OS.

+10
source share

In JavaScript (according to this WebSite: http://www.albionresearch.com/misc/urlencode.php ), I get the following:% E9l% E9phant.

This page is incorrect. JavaScript also uses UTF-8, as .NET does by default. Try it yourself:

 javascript:alert(encodeURIComponent('éléphant')) %C3%A9l%C3%A9phant 

Today's URLs are UTF-8. Do not try to use cp1252. UTF-8 is your friend. Trust UTF-8!

+6
source share

Link:

 js: %E9 l %E9 phant .net: %c3 %a9 l %c3 %a9 phant 

The difference is that it is UTF-8 URL UTF-8 , and the other is ANSI URL encoding.

In .NET try:

 Dim a As String = System.Web.HttpUtility.UrlEncode( _ "éléphant", _ Text.Encoding.Default) 

I get

  %e9 l %e9 phant 

. This matches the string provided for JavaScript, except in the case of a hexadecimal character.

+5
source share

Encoding.Default will only work for you if your current system code page is set to Western European. Now this may be important if Javascript also runs on the same computer as the .NET encoder, but if not, then you can force the code page into Western European:

 System.Web.HttpUtility.UrlEncode("éléphant", Encoding.GetEncoding(1252)); 
+3
source share

You can also try using base64 encoding.

There is a previous post that deals with its implementation in JavaScript.

Like in .NET, there are many examples showing how to do this. Here is one I found from Google.

Of course, strings may be slightly larger than urlencoding. However, they will be confusing, which may be an advantage depending on the application.

+2
source share

All Articles