NameValueCollection to URL Query?

前端 未结 12 2081
温柔的废话
温柔的废话 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: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();
    }
    

提交回复
热议问题