Encoding parameters for a URL

103,247

Solution 1

I would recommend Uri.EscapeDataString instead of using HttpUtility functions. See discussion in Server.UrlEncode vs. HttpUtility.UrlEncode.

Solution 2

Try to use the UrlPathEncode() method. View the remarks at: http://msdn.microsoft.com/en-us/library/h10z5byc.aspx

Quote:

You can encode a URL using with the UrlEncode() method or the UrlPathEncode() method. However, the methods return different results. The UrlEncode() method converts each space character to a plus character (+). The UrlPathEncode() method converts each space character into the string "%20", which represents a space in hexadecimal notation. Use the UrlPathEncode() method when you encode the path portion of a URL in order to guarantee a consistent decoded URL, regardless of which platform or browser performs the decoding.

Share:
103,247
user70192
Author by

user70192

Updated on July 08, 2022

Comments

  • user70192
    user70192 almost 2 years

    I have a Silverlight application that is building a URL. This URL is a call to a REST-based service. This service expects a single parameter that represents a location. The location is in the form of "city, state". To build this URL, I'm calling the following code:

    string url = "http://www.example.com/myService.svc/";
    url += HttpUtility.UrlEncode(locationTextBox.Text);
    

    If a user enters "chicago, il" into locationTextBox, the result looks like this:

    http://www.example.com/myService.svc/chicago%2c+il
    

    In reality though, I was kind of expecting the URL to look like;

    http://www.example.com/myService.svc/chicago,%20il
    

    When testing my service via the browser URL, the one I am expecting works. However, the URL that is being generated is not working. What am I doing wrong?