17

I want its output as uppercase. This is what I get on Server.UrlEncode("http://"):

http%3a%2f%2f

but I need:

http%3A%2F%2F

Is there built-in solution in C#?


The url encoded shall serve as signature base string (input to signature algorithm) to create digest (hash). The hash will then be verified by other system (java,php,etc), so they need to recreate the hash by signature reconstruction first.

nixda
  • 2,654
  • 12
  • 49
  • 82
lax
  • 189
  • 1
  • 5
  • Does the case matter for all the %escaped characters? – agent-j Jun 16 '11 at 11:34
  • 11
    This matters for something like OAuth where the difference between `%2f` and `%2F` is enough to make your signature invalid - http://oauth.net/core/1.0/#encoding_parameters – Nathan Friedly Jul 06 '13 at 00:00

5 Answers5

32

This will uppercase all escaped characters in your string.

string url = "http://whatever.com/something";
string lower = Server.UrlEncode(url);
Regex reg = new Regex(@"%[a-f0-9]{2}");
string upper = reg.Replace(lower, m => m.Value.ToUpperInvariant());
salle55
  • 2,101
  • 2
  • 25
  • 27
agent-j
  • 27,335
  • 5
  • 52
  • 79
  • that's its agent-j, but without extra ")", Thanks! – lax Jun 16 '11 at 12:45
  • thanks for this. For some reason Twitter's OAuth requires the escaped characters to be in uppercase or else it'll give you 401 unauthorized – SAGExSDX Jun 12 '13 at 20:54
  • Thanks! (BTW, the reason this is necessary for OAuth is that the entire URL ("http://" and all) is URLEncoded and then signed. The OAuth 1.0 spec requires uppercase hexadicemal for encoded characters, but the .net UrlEncode produces lowercase - the difference causes the signatures to not match.) – Nathan Friedly Jul 06 '13 at 00:04
  • @SAGExSDX: I have uppercase the url that needed to create the oauth_signature. But it still give me the 401 error. If you have the C# code, can you share it me please ? – Cham Oct 13 '15 at 10:48
  • @user1457039 var lower = HttpUtility.UrlEncode(strText); var reg = new Regex(@"%[a-f0-9]{2}"); return reg.Replace(lower, m => m.Value.ToUpperInvariant()); It's the same as the above answer. – SAGExSDX Oct 17 '15 at 06:26
24
Uri.EscapeDataString("http://")

This code return

http%3A%2F%2F
PlushEngineCell
  • 775
  • 1
  • 7
  • 14
3

This is very easy

Regex.Replace( encodedString, @"%[a-f\d]{2}", m => m.Value.ToUpper() )

I.e. replace all hex letter-digit combinations to upper case

SeregaKa
  • 61
  • 3
3

I encountered the same problem, I found the answer in this link:

WebUtility.UrlEncode or HttpUtility.UrlEncode

in-short you can use:

System.Net.WebUtility.UrlEncode

which encodes into uppercase hex values

0

Assuming "http" is always the first four characters then you simply split the string after "http", UrlEncode that part and then call ToUpper() on it. Then join back together with "http" as your prefix.

Dan Diplo
  • 25,076
  • 4
  • 67
  • 89