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.
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.
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.
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);
}
}
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With