C O
C O

Reputation: 55

C# HttpClient URI is not escaping properly

I'm trying to get my URL to escape but it's not working properly. Ironically, on my MacBook when I execute this part of code

Uri url = new Uri("http://www.example.com/?i=123%34", true);
// it returns http://www.example.com/?i=123%34 which is exactly what I want.

The problem is that my IDE says it's obsolete and it does not work on my Windows machine. It's the exact same project, and IDE. So I tried to find a solution, which someone suggested

Uri uri = new Uri(Uri.EscapeUriString("http://www.example.com/?i=123%34")); 
// this returns http://www.example.com/?i=123%2534 which is what I DONT want.

So how do I approach this issue? I looked all over the web and I can't find any solutions. I need to know how to properly escape this URL. The second method posted above does not work like the first method above.

I verified the GET requests via Fiddler, so everything is indeed happening.

Update:

Again, I need the server to receive the URL exactly how the string is declared. I want the server to handle the conversion. I cannot substitute %25 for the % symbol. It MUST be received exactly how I the string is declared. Additionally, "http://www.example.com/?i=1234" is NOT what I want either.

Upvotes: 2

Views: 2250

Answers (2)

Pranav Negandhi
Pranav Negandhi

Reputation: 1624

The problem is with the configuration of your web server on Windows, that allows double escaping. Your original URL is http://www.example.com/?i=123%34, which when unescaped, becomes http://www.example.com/?i=1234.

Your web server on Windows, on the other hand, escapes the % character again instead of unescaping %34. Thus, it turns into http://www.example.com/?i=123%2534.

This is why you should not use characters like % in the URL before it gets escaped.

Edit -

I typed the following two URLs in Firefox to see how the parameters are received on the server.

The value of i in http://www.example.com/?i=123%34 is 1234.

The value of i in http://www.example.com/?i=123%2534 is 123%34

If the server must receive the % character, it must be escaped in order for it to be dispatched over HTTP. There's literally no other way to send it over the wire. If you don't escape the % character, it will be treated as an escape sequence along with 34 and automatically turn into 4 on the server.

If your network inspector shows you unescaped text in the request, it's because it's prettifying the URL before displaying it to you.

Upvotes: 1

Kolichikov
Kolichikov

Reputation: 3020

If you are okay with the string reading ht tp://www.example.com/?i=1234, you can try Uri url = new Uri(Uri.UnescapeDataString("http://www.example.com/?i=123%34"));

Upvotes: 0

Related Questions