Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UrlPathEncode do not escape spaces

Tags:

c#

I have Url with space and would like to replace spaces with %20(escape them). UrlPathEncode should do that but it do not works on url below which has spaces. Can someone explain why it is not working?

System.Web.HttpUtility.UrlPathEncode("http://a1.quickcatchlabs.com/phototemplates/football_blimp_1.html?i_url=http://lh3.ggpht.com/yf5lVBB_WNBvBHT1HoIzY1SG0-PY5zRCobP3vBacuSk9N346F7CeAIRSFOltR6ZC1-yf-MNKAcAd7bAZ_A=s612-c&i_name=Patriots  vs Redskins&i_venue_name=Gillette Stadium &i_venue_address=Foxborough , MA&d_Score_0=34&d_Score_1=27&d_Period_0=Final&p_name_0=Patriots &p_name_1=Redskins");
like image 253
Tomas Avatar asked Dec 16 '11 14:12

Tomas


People also ask

How do you escape spaces in a URL?

URLs cannot contain spaces. URL encoding normally replaces a space with a plus (+) sign or with %20.

What is %20 in query string?

According to the W3C (and they are the official source on these things), a space character in the query string (and in the query string only) may be encoded as either " %20 " or " + ".

How do you handle space in query string?

Spaces are not allowed in URLs. They should be replaced by the string %20. In the query string part of the URL, %20 can be abbreviated using a plus sign (+).

How are URL parameters passed with spaces?

Yes, the space is usually encoded to "%20" though. Any parameters that pass to a URL should be encoded, simply for safety reasons.


2 Answers

As the name implies, UrlPathEncode encodes the path. Just the path, not the query portion of the URL. If you add a space to path and run that code again, you will see that the space in the path portion is replaced by a %20, but the spaces in the query portion are not.

If you replace the call to UrlPathEncode with one to Uri.EscapeUriString, it will correctly encode the entire URL, not just the path.

like image 62
dgvid Avatar answered Oct 03 '22 23:10

dgvid


You should call Uri.EscapeDataString.

like image 28
SLaks Avatar answered Oct 03 '22 23:10

SLaks