samn
samn

Reputation: 2817

Querystring not working, ampersands converted to %20

I have the following problem in C#, when I pass values with the querystring from an email like this:

http://www.website.com?firstname=Joe&lastname=Average

The values are shown on the website like this:

http://www.website.com?firstname%3d%24Joe%24%26lastname%3d%24Average

So basically the URL's are being encoded, but some parts shouldn't be encoded. I've tried & instead of &, but no luck either.

Upvotes: 0

Views: 1414

Answers (2)

Rubens Farias
Rubens Farias

Reputation: 57996

You're encoding entire querystring, and not only their values. You should do something like

var values = new Dictionary<string, string>();
values.Add("firstname", "Joe");
values.Add("lastname", "Average");
var querystring = String.Join("&", values.Select(pair => 
    pair.Key + "=" + HttpUtility.UrlEncode(pair.Value)).ToArray());

Upvotes: 0

Sebastian Siek
Sebastian Siek

Reputation: 2075

Any values passed to/from URL should be Url Encoded/Decoded. On the other hand when displaying text on the page (HTML) you should use HtmlEncode.

You can find the methods in namespace System.Web:

  • HttpUtility.UrlEncode.
  • HttpUtility.UrlDecode.
  • HttpUtility.UrlHtmlEncode.

etc.

Hope that helps.

Upvotes: 3

Related Questions