How to get a list of all the url parameters with t

2020-07-11 08:12发布

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.

3条回答
贪生不怕死
2楼-- · 2020-07-11 08:37

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]);
查看更多
混吃等死
3楼-- · 2020-07-11 08:43

The HttpRequest.QueryString object is already a collection. Basically a NameValueCollection. Check here for a more detailed explanation on MSDN. To convert this collection in to a dictionary you could add an extension method as follows.

    public static class NameValueCollectionExtension
    {

        public static IDictionary<string, string> ToDictionary(this NameValueCollection sourceCollection)
        {
            return sourceCollection.Cast<string>()
                     .Select(i => new { Key = i, Value = sourceCollection[i] })
                     .ToDictionary(p => p.Key, p => p.Value);

        }

    }

Then you could basically just do the following since Request.QueryString is basically a NameValueCollection

IDictionary<string,string> dc = Request.QueryString.ToDictionary();
查看更多
看我几分像从前
4楼-- · 2020-07-11 08:56

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);
   }
}
查看更多
登录 后发表回答