64

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?

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
user70192
  • 13,786
  • 51
  • 160
  • 240

3 Answers3

100

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

Community
  • 1
  • 1
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • 3
    I tried this and still got the error for '#' character. Pls see my question here: http://stackoverflow.com/questions/31699335/regex-to-validate-a-string-that-will-be-one-of-the-of-wcf-rest-method-url-parame – Muhammedh Jul 30 '15 at 14:57
7

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.

JochemKempe
  • 2,566
  • 2
  • 16
  • 12
0

The safest bet is to use the AntiXss library. It has more standard (and secure) versions for encoding contents to various purposes (like Url encodes, Html and HtmlAttribute encodes, and more). there's the old 3.1 version available for download from MS site (http://www.microsoft.com/downloads/details.aspx?FamilyId=051ee83c-5ccf-48ed-8463-02f56a6bfc09), which will work with older .NET versions, and the new one at http://wpl.codeplex.com/

Ken Egozi
  • 1,825
  • 11
  • 14