Click here to Skip to main content
Click here to Skip to main content

A Small Class for Simplifying the Work with URL Parameters

By , 4 Apr 2010
 
An URL inside the Microsoft Internet Explorer Address bar

Introduction

(For the latest changes, please see the History section below.)

If you are working with URLs from within ASP.NET, you probably often need to read different URL parameters. E.g., you could read the value of the "name1" parameter out of the QueryString collection of your Page class (or, to be more precise, from the Request property of your Page class):

private void Page_Load(
    object sender, 
    System.EventArgs e )
{
    string value1 = Request.QueryString["name1"];
 
    // ... Further processing of the value1 variable ... 
}

In my projects, I often need the ability to write URL parameters, e.g., for outputting a URL on a page or for redirecting to another page with the appropriate parameters. This article introduces a class QueryString which I wrote in order to simplify my life a little bit.

Some Examples

Before examining the QueryString class in more detail, first some examples of how to use it are shown.

Example 1 - Manipulate an attribute value

Create a QueryString and simply let itself fill with the parameters of the current page:

private void Page_Load(
    object sender, 
    System.EventArgs e )
{
    // Let the object fill itself 
    // with the parameters of the current page.
    QueryString qs = new QueryString();
 
    // Read a parameter from the QueryString object.
    string value1 = qs["name1"];
  
    // Write a value into the QueryString object.
    qs["name1"] = "This is a value";
  
    // Redirect with the current content of the QueryString object.
    // In this example, since the BeforeUrl property is not modified,
    // it will redirect to the current page itself, but with the
    // "name1" parameter set to the new value.
    Response.Redirect( qs.All, true );
}

As you can see, you can simply modify a parameter's value by assigning it to the appropriate parameter name by using the [] operator. The All property returns the complete URL that is stored inside the QueryString object including the latest (possibly modified) parameters.

Example 2 - Removing parameters

To remove a certain parameter from the QueryString object, call the RemoveParameter method, specifying the name of the parameter to remove:

private void Page_Load(
    object sender, 
    System.EventArgs e )
{
    // Let the object fill itself 
    // with the parameters of the current page.
    QueryString qs = new QueryString();
 
    // Read a parameter from the QueryString object.
    string value1 = qs["name1"];
  
    // Now remove the parameter.
    qs.RemoveParameter( "name1" );
   
    // This has the same effect as RemoveParameter() method:
    qs["name1"] = null;
  
    // ... Further processing of the value1 variable ... 
}

The Class in Brief

The most common use of the class was already described in the previous section. It should be simple to use, n'est pas? Nevertheless, here is an (incomplete) overview of the most usable members:

Constructors

The following constructors exists.

  • public QueryString() - Empty constructor, fills itself with the parameters of the current page (if any)
  • public QueryString( System.Web.UI.Page currentPage ) - Constructs with the parameters of the given page
  • public QueryString( string url ) - Constructs with the parameters from the given URL
  • public QueryString( Uri uri ) - Constructs with the parameters from the given URI

Methods for reading from a given URL

By using the following methods, you can achieve similar results as with the constructors, but after the object is already constructed.

  • public void FromUrl( System.Web.UI.Page currentPage ) - Fills with the parameters of the given page
  • public void FromUrl( string url ) - Fills with the parameters from the given URL
  • public void FromUrl( Uri uri ) - Fills with the parameters from the given URI

Miscellaneous operations

Use the following methods for further operations.

  • public bool HasParameter( string parameterName ) - Check whether a given parameter is present (i.e. is non-null and non-empty-string)
  • public void RemoveParameter( string name ) - Removes a parameter from the current parameter collection. Does nothing if the parameter is not present
  • public void RemoveAllParameters() - Removes all parameters from the current parameter collection

Miscellaneous properties

Use the following properties for accessing various values.

  • public string this [string index] - Gets or sets a parameter value by the given parameter name. If the parameter does not exists, get returns string.Empty (i.e. not null).
  • public string BeforeUrl - Gets or sets the the "base" part of the URL returned by the All property. E.g. set this to "http://www.myserver.com/mypage.aspx"
  • public string All - Gets the complete URL that is currently stored inside the object. This is the value of the All property plus the current parameters. E.g. returns "http://www.myserver.com/mypage.aspx?name1=value1&name2=someOtherValue".

Conclusion

In this small article, I've shown you a class that simplifies the reading and writing of URL parameter values. For me, this class is around about approximately two years and helped me save a lot of coding time (well, at least a bit...). Hopefully it is useful for you, too.

For questions, comments and remarks, please use the commenting section at the bottom of this article.

History

  • 2010-04-05: Added new version that adds several new methods (like a HTTP 301 redirect, which is good for SEO) and makes use of the concept of a Fluent interface
  • 2005-01-06: Corrected some very small spelling errors
  • 2004-12-30: Added fix and suggestion from Chris Maunder
  • 2004-12-14: Created first version of article

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Uwe Keim
Chief Technology Officer Zeta Producer Desktop CMS
Germany Germany
Member
Uwe does programming since 1989 with experiences in Assembler, C++, MFC and lots of web- and database stuff and now uses ASP.NET and C# extensively, too. He has also teached programming to students at the local university.
 
In his free time, he does climbing, running and mountain biking. Recently he became a father of a cute boy.
 
Some cool, free software from us:
 
Free Test Management Software - Intuitive, competitive, Test Plans. Download now!  
Homepage erstellen - Intuitive, very easy to use. Download now!  
Send large Files online for free by Email
Some random fun stuff in German

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionURL REDIRECTIONmemberMember 917112831 Jul '12 - 19:58 
What is URL REDIRECTION?How can i use this concept in my .net?
my task is i have generated one url like this "http://example.com/"
I am passing one pearameter like "http://example.com/Empno=1"
I want to display Ename in Database table that corresponding "Empno"
plz Help me Give me one simple example
 
I am new this concepts
plz Help me send source code to my mailID:mandla.anilbabu@gmail.com
GeneralMy vote of 5memberSunasara Imdadhusen4 Jan '11 - 22:13 
Nice work!
GeneralParameters Encode / DecodememberMember 32658741 Sep '10 - 23:50 
Hello.
I'd like to create Encoded params, and reading back Decoded params (with HttpUtility UrlEncode / UrlDecode) by this class.
Is it possible ?
 
Thanks
GeneralRe: Parameters Encode / DecodemvpUwe Keim2 Sep '10 - 0:31 
Its done automatically, no need to do it at all.
My personal 24/7 webcam  
Free Test Management Software - Intuitive, competitive, Test Plans. Download now!  
Free Website Builder - Intuitive, very easy to use. Download now!

GeneralRe: Parameters Encode / DecodememberMember 32658742 Sep '10 - 4:51 
Thanks for the answer.
I have another question.
In some cases, I would that when I init the class, it doesn't read the actual page params but create a new empty querystring.
How can I do it?
 
Thanks for your help, great work by the way.
GeneralRe: Parameters Encode / DecodememberMember 32658742 Sep '10 - 4:55 
I found this method: RemoveAllParameters().
Is it the best practice for this?
AnswerA way to remove parameter-name hardcode.membervalera.kolupaev10 Dec '09 - 0:54 
It's a good idea to encapsulate query-string works in separate class, but you can go further and add compile-time type checking to your's urls. I have blogged about it here.
GeneralThanksmemberColinBashBash26 May '09 - 11:02 
Thanks, that's just what i needed.
 
if (Membership.ValidateUser(Request["u"], pass)) {
FormsAuthentication.SetAuthCookie(Request["u"], false);
 
string redirect = FormsAuthentication.GetRedirectUrl(Request["u"], false);
QueryString q = new QueryString(redirect);
q.RemoveParameter("p");
q.RemoveParameter("u");
Response.Redirect(q.All);
}
 
... ie: the incredibleness of q.RemoveParameter();
GeneralRe: ThankssitebuilderUwe Keim26 May '09 - 11:04 
Thanks for your feedback Smile | :) . Glad you liked it!
 
My personal 24/7 webcam - Always live Wink | ;-)
Zeta Test - Intuitive, competitive Test Management environment. Download now!
Zeta Producer Desktop CMS - Intuitive, completely easy-to-use. Download now!

GeneralRe: ThanksmvpUwe Keim4 Apr '10 - 21:54 
Thanks to the Fluent interface I've just uploaded, you could now write:
new QueryString(redirect)
    .RemoveParameter("p")
    .RemoveParameter("u")
    .Redirect();
Hope you like it Smile | :)
My personal 24/7 webcam
Free Test case management - Intuitive, competitive, Test Plans. Download now!
Free homepage builder - Intuitive, very easy to use. Download now!

QuestionCompatibility and optimizationsmemberPeterB7225 May '09 - 2:52 
Hi,
 
I know this is a very old class. Maybe better versions exist, but I haven't find them. Looking at your code I have a few remarks/questions:
 
* Why are you not using StringBuilder in the Make() routines?
 
* Microsoft's HttpRequest.QueryString property does NOT include the question mark ("?") as part of the querystring, while your code does. It would be great if this could be made compatible.
 
* Valid querystrings can contain parameters without value (example.html?q) and multiple parameters with the same name (example.html?q=1&q=2&q=3). Various routines in your code do not take this into account.
 
* Your code also munges the hash part of the URL (everything that comes after the "#" character, as in example.html?q=1#test).
GeneralGreat workmemberShahedul Huq Khandkar24 Jul '06 - 21:39 
Thanks for making my life easier.;)
GeneralRe: Great worksitebuilderUwe Keim24 Jul '06 - 21:44 
Thanks for your feedback Smile | :) .
 
Be sure to check out my ZetaLibNet [^] article which always contains the latest version of the QueryString class. (You can use it separately without requiring the whole library to load).
 
--
Try our Windows-based CMS: www.zeta-producer.com
See me working: www.magerquark.com

QuestionDo you have it in vb.net?memberHamidTheProgrammer20 Sep '05 - 6:55 
Hi:
This is exactly what I am looking for, but I couldn't use it since I am using vb.net/asp.net Sigh | :sigh: . Do you have the vb.net version?
 
HamidTheProgrammer
AnswerRe: Do you have it in vb.net?sitebuilderUwe Keim20 Sep '05 - 8:18 
Thanks, Hamid!
 
You could simply create a C#-DLL with my class and then use this class from within VB.NET.
 
Everything will work then! I do this the same for me with code which is only available in VB.NET.
 
--
Affordable Windows-based CMS for only 99 €: try www.zeta-producer.com for free!
 

AnswerRe: Do you have it in vb.net?memberGavin Harriss19 Feb '07 - 15:35 
Only 2 years too late replying, but for the benefit of others still seeking an answer to this question...
 
This does a good job: http://www.kamalpatel.net/ConvertCSharp2VB.aspx[^]
 
Though you'll have to remove all <summary></summary> etc. tags as the ASP.NET page throws an error as it thinks you're doing naughty things with the input form.
 

Gavin Harriss
Portfolio: gavinharriss.com


GeneralA better C# to VB.NET convertermemberGavin Harriss19 Feb '07 - 15:54 
Actually, this one's far more forgiving...
http://www.developerfusion.co.uk/utilities/convertcsharptovb.aspx[^]
 

Gavin Harriss
Portfolio: gavinharriss.com


GeneralPageMethods helps with URLssussAnonymous17 May '05 - 14:00 
Interesting work. Those who want to go further with URL handling in ASP.NET, can take a look at PageMethods. PageMethods enables well-defined URLs using methods and attributes.
GeneralRe: PageMethods helps with URLssitebuilderUwe Keim17 May '05 - 18:30 
If you already do advertising, next time include the URL Wink | ;-)
 
http://metasapiens.com/PageMethods/ [^]
 
--
Affordable Windows-based CMS for only 99 €: try www.zeta-producer.com for free!
 

Generalquerystring and postbackmembermagister11 May '05 - 3:54 
I like this and think it is useful, but I notice every time I pass querystring parameters back to the page I am on I loose my page states...ie. Page.IsPostBack is false...
 
It would be good to be able to pass parameters back to a page without having this happen in some cases.
GeneralRe: querystring and postbacksitebuilderUwe Keim11 May '05 - 18:25 
It could probably register itself somehow in the postback chain. E.g. by providing an extended version that is droppable as a user control on a form.
 
But then,my title "...a small class..." is no longer true Wink | ;-)
 
So currently I have no need for this but the idea is very good. Thanks for the suggestion!
 
--
Affordable Windows-based CMS for only 99 €: try www.zeta-producer.com for free!
 

GeneralQuite a useful class, done something similarmemberSam Collett10 May '05 - 23:41 

I'm sure this is very helpful to many people. I have done something similar in July 2004 (with an update in September 2004), which I use extensively (mine only has two constructors - one with no paramater to get the current page, and one with a string - supply 'page.aspx' to set to another page with the current page parameters, or 'page.aspx?q=1&q2=4' to set new parameters).

Url Manipulation v2 (C#)

Url Manipulation (C#)

Edit:
New Version


GeneralRe: Quite a useful class, done something similarsitebuilderUwe Keim10 May '05 - 23:58 
Great class you've done! Maybe I can merge some of your code into my class if it fits...
 
Thanks for sharing!
 
--
Affordable Windows-based CMS for only 99 €: try www.zeta-producer.com for free!
 

GeneralGreat workmemberNoman Nadeem25 Apr '05 - 20:23 
Great work. I just wish I could've stumbled accross this article a month ago !
 
regards,
Noman Nadeem Sleepy | :zzz:
GeneralRe: Great worksitebuilderUwe Keim28 Apr '05 - 1:29 
Thank you! Big Grin | :-D
 
--
Affordable Windows-based CMS for only 99 €: try www.zeta-producer.com for free!
 

QuestionHow to retrieve only the parameters ?memberJohann Frot6 Apr '05 - 5:42 
Hi,
 
your code is exactly (and even more) what I needed ! Thanks a lot. Big Grin | :-D
 
One question : I know how to retrieve the "base" url --> member BeforeUrl
I also know how to get the whole Url --> member All
 
Is there a way to get only the parameters after the "?" ? I need this in order to pass them to an other page instead of the same one with the All.
 
thanks for your help
 
Johann
AnswerRe: How to retrieve only the parameters ?sitebuilderUwe Keim6 Apr '05 - 17:00 
Thank you! Big Grin | :-D
 
You can use the Make() function to get the current contained parameters built as one ready-to-use string that contains only the parameters but including the "?".
 
So you could write:
string s = myQS.Make().TrimLeft( '?' );
if you want to get the parameters without the leading questionmark.
 
--
Affordable Windows-based CMS for only 99 €: try www.zeta-producer.com for free!
 

GeneralRe: How to retrieve only the parameters ?memberJohann Frot6 Apr '05 - 20:46 
Thanks, it works !
GeneralPerfect!memberIPC200030 Mar '05 - 23:07 
Just what I needed. Thanks!
GeneralRe: Perfect!sitebuilderUwe Keim31 Mar '05 - 0:05 
Thanks for your feedback! Good to hear that my work is actually being used Smile | :)
 
--
Affordable Windows-based CMS: www.zeta-producer.com
 

GeneralValidationsussYussef18 Jan '05 - 3:50 
First of all: Great class! I'm thinking of adding event driven validation to this class. The idea is that different controls (ASCX files) can hook to the validation event to check wether or not their variables are correct (not tampered with by the user or something like that).
 
Each control could call somthing like Querystring.IsValid to check wether or not the complete querystring is valid and decide to do a redirect or not.
 
I have to work this out, but what do you think of the idea? Smile | :)
GeneralRe: ValidationsitebuilderUwe Keim18 Jan '05 - 17:25 
Nice idea, but probably to complicated/expensive in terms of performance.
 
Every of your controls could create a local instance of the class upon loading and check there directly...
 
--
Affordable Windows-based CMS: www.zeta-producer.com
 

Generalretrieving passed param values from redirected pagemembermisha20006 Jan '05 - 3:40 
I am adding my parameters with values on first page (QSPage1) and redirecting to second page (QSPage2), this bit is successful as the url is correct with the appropriate parameters but what am I doing wrong when I try to retrieve a parameter from the QueryString on my page_load of the second page as the value returned is empty("")?
 
QueryString qsParams = new QueryString("../TestControls/QSPage1.aspx");
 
lblParam.Text = qsParams["qs1"];
 
I tried using the FromUrl Method as well.
Or have I just caught the wrong end of the stick?Confused | :confused:
GeneralRe: retrieving passed param values from redirected pagesitebuilderUwe Keim6 Jan '05 - 3:51 
On QSPage2 simply write:
QueryString qsParams = new QueryString();
 
lblParam.Text = qsParams["qs1"];
I.e. with no parameters to the constructor. The object will automatically populate itself from the current page with the current parameters.
 
--
Affordable Windows-based CMS: www.zeta-producer.com
 

GeneralRe: retrieving passed param values from redirected pagemembermisha20006 Jan '05 - 22:34 
Thank youSmile | :)
 
In what condition would one use the constructor with the url parameter as I had tried earlier?
GeneralRe: retrieving passed param values from redirected pagesitebuilderUwe Keim7 Jan '05 - 7:26 
misha2000 wrote:
In what condition would one use the constructor with the url parameter as I had tried earlier?
 
Hmmm. Difficult to say. I don't know whether I used it at all, but it could be useful some day Big Grin | :-D .
 
--
Affordable Windows-based CMS: www.zeta-producer.com
 

GeneralMinor bug fixadminChris Maunder29 Dec '04 - 16:28 
In FromUrl(string url) at the lines
if ( url.Length>0 && url.Substring( 0, 1 )=="?" )
{ 
    url = url.Substring( 2 );
}
the Substring( 2 ); should be Substring( 1 );.
 
I also added:
/// <summary>
/// Appends a query string onto an existing URL. Takes care 
/// of worrying about whether to add "&..." or "?..."
/// </summary>
/// <param name="URL">The URL to be extended</param>
/// <param name="QS">The Querystring to add</param>
/// <returns>The complete URL</returns>
static public string AppendQueryString(
            string URL,
            string QS )
{ 
    string result = URL.TrimEnd( '?', '&' );
    if (result.IndexOf("?") >= 0)
        return URL + "&" + QS;
    else
        return URL + "?" + QS;
}

 
cheers,
Chris Maunder
GeneralRe: Minor bug fixsitebuilderUwe Keim29 Dec '04 - 16:55 
Thanks Chris, I will add the fixes to my code!
 
--
Affordable Windows-based CMS: www.zeta-producer.com
 

GeneralRe: Minor bug fixsitebuilderUwe Keim29 Dec '04 - 23:56 
Added Big Grin | :-D .
 
It really does pay off for me to publish code! Even only that fix from you could save me from trouble in the future when using the component in my own projects!
 
--
Affordable Windows-based CMS: www.zeta-producer.com
 

GeneralGood timing!adminChris Maunder25 Dec '04 - 23:32 
I was just about to code pretty much the same abstraction but you've not only saved me the trouble, you've done a far better job than I was planning on doing.
 
I think we need a CodeProject Legend Icon Wink | ;)
 
cheers,
Chris Maunder
GeneralRe: Good timing!sitebuilderUwe Keim26 Dec '04 - 18:05 
Thank you Smile | :)
 
--
Affordable Windows-based CMS: www.zeta-producer.com
 

GeneralGood Idea!memberWebdiyer14 Dec '04 - 14:04 
A very good idea!how about add it as a property of the common page class?
 
AspNetPager-the final solution for asp.net paging!
-----------------
www.webdiyer.com!
GeneralRe: Good Idea!sitebuilderUwe Keim14 Dec '04 - 17:27 
Thank you Smile | :)
 
Very good idea! In deed, I did it in my projects and added a QS property (public QueryString QS { get { ... } }) to my Page-derived class.
 
I just wanted to keep this article/examples simple.
 
--
Affordable Windows-based CMS: www.zeta-producer.com
 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 5 Apr 2010
Article Copyright 2004 by Uwe Keim
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid