How to escape url encoding?
Solution 1
Since .NET Framework 4.5 you can use WebUtility.UrlEncode
.
It resides in System.dll
, so it does not require any additional references.
It properly escapes characters for URLs, unlike Uri.EscapeUriString
It does not have any limits on the length of the string, unlike Uri.EscapeDataString
, so it can be used for POST requests
System.Net.WebUtility.UrlEncode(urlText)
Another option is
System.Uri.EscapeDataString()
Solution 2
Uri.EscapeDataString() and Uri.UnescapeDataString() are safe comparing to UrlEncode/UrlDecode methods and does not convert plus characters into spaces when decoding.
Some details from another user: http://geekswithblogs.net/mikehuguet/archive/2009/08/16/134123.aspx
Solution 3
Just use HttpUtilty's UrlEncode
method right before you hand off the url;
string encoded = HttpUtility.UrlEncode(url);
omega
Updated on July 18, 2022Comments
-
omega almost 2 years
I am creating a link that creates URL parameters that contains links with URL parameters. The issue is that I have a link like this
http://mydomain/_layouts/test/MyLinksEdit.aspx?auto=true&source= http://vtss-sp2010hh:8088/AdminReports/helloworld.aspx?pdfid=193 &url=http://vtss-sp2010hh:8088/AdminReports/helloworld.aspx?pdfid=193%26pdfname=5.6%20Upgrade &title=5.6 Upgrade
This link goes to a bookmark adding page where it reads these parameters.
auto
is wheather to read the following parameters or notsource
is where to go after you finish adding or cancellingurl
is the bookmark linktitle
is the name of the bookmarkThe values of
url
andtitle
get entered into 2 fields. Then the user has to clicksave
orcancel
. The problem is when the bookmark page enters the values into the field, it will decode them. Then if you try to save, it will won't let you save because thepdfname
value in theurl
value has a space in it. It needs the link to not have any spaces. So basically, I want it so that after it enters it in the field, it will still be a%20
instead of a space.There isn't a problem with
source
,auto
, ortitle
, just theurl
...Is there a way to solve this? Like maybe a special escape character I can use for the
%20
?Note: I cannot modify the bookmark page.
I am using c#/asp.net to create the link and go to it.
Thanks