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
Tilføj en kommentar