NameValueCollection to URL Query?

前端 未结 12 2044
温柔的废话
温柔的废话 2020-11-28 05:36

I know i can do this

var nv = HttpUtility.ParseQueryString(req.RawUrl);

But is there a way to convert this back to a url?

v         


        
相关标签:
12条回答
  • 2020-11-28 06:20

    You can use.

    var ur = new Uri("/page",UriKind.Relative);
    

    if this nv is of type string you can append to the uri first parameter. Like

    var ur2 = new Uri("/page?"+nv.ToString(),UriKind.Relative);
    
    0 讨论(0)
  • 2020-11-28 06:23

    Simply calling ToString() on the NameValueCollection will return the name value pairs in a name1=value1&name2=value2 querystring ready format. Note that NameValueCollection types don't actually support this and it's misleading to suggest this, but the behavior works here due to the internal type that's actually returned, as explained below.

    Thanks to @mjwills for pointing out that the HttpUtility.ParseQueryString method actually returns an internal HttpValueCollection object rather than a regular NameValueCollection (despite the documentation specifying NameValueCollection). The HttpValueCollection automatically encodes the querystring when using ToString(), so there's no need to write a routine that loops through the collection and uses the UrlEncode method. The desired result is already returned.

    With the result in hand, you can then append it to the URL and redirect:

    var nameValues = HttpUtility.ParseQueryString(Request.QueryString.ToString());
    string url = Request.Url.AbsolutePath + "?" + nameValues.ToString();
    Response.Redirect(url);
    

    Currently the only way to use a HttpValueCollection is by using the ParseQueryString method shown above (other than reflection, of course). It looks like this won't change since the Connect issue requesting this class be made public has been closed with a status of "won't fix."

    As an aside, you can call the Add, Set, and Remove methods on nameValues to modify any of the querystring items before appending it. If you're interested in that see my response to another question.

    0 讨论(0)
  • 2020-11-28 06:25

    This should work without too much code:

    NameValueCollection nameValues = HttpUtility.ParseQueryString(String.Empty);
    nameValues.Add(Request.QueryString);
    // modify nameValues if desired
    var newUrl = "/page?" + nameValues;
    

    The idea is to use HttpUtility.ParseQueryString to generate an empty collection of type HttpValueCollection. This class is a subclass of NameValueCollection that is marked as internal so that your code cannot easily create an instance of it.

    The nice thing about HttpValueCollection is that the ToString method takes care of the encoding for you. By leveraging the NameValueCollection.Add(NameValueCollection) method, you can add the existing query string parameters to your newly created object without having to first convert the Request.QueryString collection into a url-encoded string, then parsing it back into a collection.

    This technique can be exposed as an extension method as well:

    public static string ToQueryString(this NameValueCollection nameValueCollection)
    {
        NameValueCollection httpValueCollection = HttpUtility.ParseQueryString(String.Empty);
        httpValueCollection.Add(nameValueCollection);
        return httpValueCollection.ToString();
    }
    
    0 讨论(0)
  • 2020-11-28 06:28

    Actually, you should encode the key too, not just value.

    string q = String.Join("&",
    nvc.AllKeys.Select(a => $"{HttpUtility.UrlEncode(a)}={HttpUtility.UrlEncode(nvc[a])}"));
    
    0 讨论(0)
  • 2020-11-28 06:28

    The short answer is to use .ToString() on the NameValueCollection and combine it with the original url.

    However, I'd like to point out a few things:

    You cant use HttpUtility.ParseQueryString on Request.RawUrl. The ParseQueryString() method is looking for a value like this: ?var=value&var2=value2.

    If you want to get a NameValueCollection of the QueryString parameters just use Request.QueryString().

    var nv = Request.QueryString;
    

    To rebuild the URL just use nv.ToString().

    string url = String.Format("{0}?{1}", Request.Path, nv.ToString());
    

    If you are trying to parse a url string instead of using the Request object use Uri and the HttpUtility.ParseQueryString method.

    Uri uri = new Uri("<THE URL>");
    var nv = HttpUtility.ParseQueryString(uri.Query);
    string url = String.Format("{0}?{1}", uri.AbsolutePath, nv.ToString());
    
    0 讨论(0)
  • 2020-11-28 06:29

    As @Atchitutchuk suggested, you can use QueryHelpers.AddQueryString in ASP.NET Core:

        public string FormatParameters(NameValueCollection parameters)
        {
            var queryString = "";
            foreach (var key in parameters.AllKeys)
            {
                foreach (var value in parameters.GetValues(key))
                {
                    queryString = QueryHelpers.AddQueryString(queryString, key, value);
                }
            };
    
            return queryString.TrimStart('?');
        }
    
    0 讨论(0)
提交回复
热议问题