Tim Boland
Tim Boland

Reputation: 10177

urlencode all querystring parameters

Is there a way to url encode the entire URL querystring without trying to urlencode each individual querystring parameters. Right now I'm having to rebuild the querystring with something like this:

foreach (string x in Page.Request.QueryString.Keys)
{
 sQueryString += x + "=" + Server.UrlEncode(Request.Params.Get(x)) + "&";
}

Upvotes: 4

Views: 4269

Answers (2)

Oleks
Oleks

Reputation: 32323

All you should to do is to get the following value:

Page.Request.Url.Query

See:

    Uri baseUri = new Uri("http://www.contoso.com/catalog/shownew.htm?date=today&<a>=<b&gt;");
    string queryString = baseUri.Query;

The queryString parameter will return ?date=today&%3Ca%3E=%3Cb%3E.

One more edit - from the MSDN:

The Query property contains any query information included in the URI. Query information is separated from the path information by a question mark (?) and continues to the end of the URI. The query information returned includes the leading question mark.

The query information is escaped according to RFC 2396 by default. If International Resource Identifiers (IRIs) or Internationalized Domain Name (IDN) parsing is enabled, the query information is escaped according to RFC 3986 and RFC 3987.

Upvotes: 6

Keith Adler
Keith Adler

Reputation: 21178

Other than using string.Format and you having an extra & at the end of your QueryString the approach above is optimal.

Upvotes: 0

Related Questions