Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a list of all the url parameters with their values in asp.net c#?

In my asp.net c# solution, I want to get a dictionary of all the url parameters, where the key is the parameter name and the value is the parameter value. How can I do this?

Thanks.

like image 305
omega Avatar asked Jun 21 '13 01:06

omega


People also ask

How can I get parameters from a URL string?

The parameters from a URL string can be retrieved in PHP using parse_url() and parse_str() functions. Note: Page URL and the parameters are separated by the ? character. parse_url() Function: The parse_url() function is used to return the components of a URL by parsing it.

How do you get multiple parameters in a URL?

To add a parameter to the URL, add a /#/? to the end, followed by the parameter name, an equal sign (=), and the value of the parameter. You can add multiple parameters by including an ampersand (&) between each one.


2 Answers

You need HttpUtility.ParseQueryString

NameValueCollection qscollection = HttpUtility.ParseQueryString(querystring);

you can use this to get the querystring value itself:

 Request.Url.Query

To put it together

NameValueCollection qscollection = HttpUtility.ParseQueryString(Request.Url.Query);

More info at http://msdn.microsoft.com/en-us/library/ms150046.aspx

The harder manual way without using the builtin method is this:

NameValueCollection queryParameters = new NameValueCollection();
string[] querySegments = queryString.Split('&');
foreach(string segment in querySegments)
{
   string[] parts = segment.Split('=');
   if (parts.Length > 0)
   {
      string key = parts[0].Trim(new char[] { '?', ' ' });
      string val = parts[1].Trim();

      queryParameters.Add(key, val);
   }
}
like image 133
ericdc Avatar answered Oct 15 '22 13:10

ericdc


I often get into the same problem. I always end up doing it like this:

Dictionary<string, string> allRequestParamsDictionary = Request.Params.AllKeys.ToDictionary(x => x, x => Request.Params[x]);

This gives all params for the request, including QueryString, Body, ServerVariables and Cookie variables. For only QueryString do this:

Dictionary<string, string> queryStringDictionary = Request.QueryString.AllKeys.ToDictionary(x => x, x => Request.Params[x]);
like image 41
Emil Ingerslev Avatar answered Oct 15 '22 13:10

Emil Ingerslev