How to escape url encoding?

omega picture omega · Jun 21, 2013 · Viewed 28.9k times · Source

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 not

source is where to go after you finish adding or cancelling

url is the bookmark link

title is the name of the bookmark

The values of url and title get entered into 2 fields. Then the user has to click save or cancel. 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 the pdfname value in the url 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, or title, just the url...

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

Answer

ericdc picture ericdc · Jun 21, 2013

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()