Link to home
Start Free TrialLog in
Avatar of dannykrouk
dannykrouk

asked on

.Net URL Encoding: should a space be '+' (plus symbol) or '%20'?

I'm using .Net libraries to encode strings for placement into URLs.  I noticed that httputility.urlencode chooses to encode the space character with '+' (a plus symbol) not '%20' (the hex value).

This is fine with me.  Except that my WCF REST service does not appear to be happy with the '+' encoding.  If I <string>.Replace the '+''s for '%20''s, everything works out just fine.  I suppose this is functional.  But, I feel like I'm missing something about how this library is supposed to work.  

I must confess to also being a bit new to WCF.  So, on the service side, I'm not clear where the decoding is happening.  But, by the time the WCF infrastructure passes the value to my code (in debug mode), it is decoded.

To make matters more confusing, if I put '+''s for spaces in the browser address window when debugging my WCF REST service, it appears to handle it fine.  It is only when the service is running in IIS that the problem occurs.  This string, when appended to the end of a URL, causes failure with IIS, but runs OK in debug mode: "Las+Vegas%2c+NV".  This string, no matter how I send it to the service, works fine: "Las%20Vegas%2c%20NV".

For those that have read this far and are wondering about the client application that is encoding the URL, I'm doing it from a SilverLight 2.0 application.

Lastly, when I preview this question and code, I've noticed that the plus symbol ('+') appears as a space (' ').  I guess Expert Exchange is urldecoding this.  Oi.  At any rate, hopefully my comments are clear enough that you can see where I mean plus symbol and where I mean space.  
// unhappy 
           //string a = HttpUtility.UrlEncode( txtInput.Text);
            
           // happy
           string a = HttpUtility.UrlEncode( txtInput.Text).Replace("+","%20");
 
            Uri u = new Uri(@"<Root of my WCF REST service>" + a);
            WebClient rest = new WebClient();
            rest.DownloadStringCompleted += new DownloadStringCompletedEventHandler(rest_DownloadStringCompleted);
            rest.DownloadStringAsync(u);

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of unmeshdave
unmeshdave
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of dannykrouk
dannykrouk

ASKER

Cha-ching!  Thanks.  That helps quite a bit.  The different behavior of the service when running in the debugger vs. in IIS was a secondary issue.  The method (and link) to which you refer are exactly what I needed.  Many thanks!