How to get URL querystring variables from a string URL with C#

16-01-2009 10:19:02

Somethings you will have to get a specific part from an url, like the query string, but you dosn't always got the possibilities to get it from Request.Querystring["Name"] if the url path is from a string.

There is many ways to solve this problem, some people likes to modify the string, and Substring the querystring part out of the relative og absolut path of the url, but there is a much more pretty way to do this. First of all, microsoft got a very nice class for url's, the System.Uri (Uniform Resource Identifier) class makes it possible for you, to check if it's actually is a url you are working with, and collect the informations you need from the link.

Here is an example os how to do it.

Uri tempUri = new Uri("http://dnohr.dk/Default.aspx?IsMonkeyBusiness=true&Name=Daniel"); string sQuery = tempUri.Query;

The 'sQuery' variable would now contain '?IsMonkeyBusiness=true&Name=Daniel', which is our query string from the absolut path i did put into my uri object.

Now you just need to parse the querystring, and here comes another nice tip, Microsoft has actually created a method for this too, just not quite known. HttpUtility.ParseQueryString is the method we are going to use to collect our specific item data from our 'sQuery'-string. Please see the example below.

string sName = HttpUtility.ParseQueryString(sQuery).Get("Name");

After using the ParseQueryString function it parse our collection as a NameValueCollection. Now it's possible to collect the item value, by just typing '.Get("item name or id")' after the ParseQueryString instance.

The result value from 'Name' item would be 'Daniel'. Hope you could use this article about collecting data from our url path, especially when you are collecting from a string URL.



Kommentarer

jesperated22-10-2009 12:10:20

thanks!!! this is really cool! saved me a lot of time!

JM22-10-2009 12:11:44

Finally a nice and simple example for ParseQueryString. Keep up the good work!

Asdrubal22-10-2009 12:18:45

Oh!! grate nice tip. Thanks for share this code.

I has been searching and searching the way to get a value from query string, saved me a lot of time.

Shanti22-10-2009 12:23:53

Excellent!!!

LeadInternet22-10-2009 12:24:14

Nice. Turns out there's a utility function for just about everything. If we only knew them all.


Tilføj en kommentar

Navn
Email (Bliver ikke vist på siden)
Hjemmeside
Hvad er 1 + 2?
Kommentar
 
Copyright © 2005 - 2010 Daniel Nøhr. All rights reserved