NameValueCollection to URL Query?

前端 未结 12 2079
温柔的废话
温柔的废话 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:19

    Make an extension method that uses a couple of loops. I prefer this solution because it's readable (no linq), doesn't require System.Web.HttpUtility, and it handles duplicate keys.

    public static string ToQueryString(this NameValueCollection nvc)
    {
        if (nvc == null) return string.Empty;
    
        StringBuilder sb = new StringBuilder();
    
        foreach (string key in nvc.Keys)
        {
            if (string.IsNullOrWhiteSpace(key)) continue;
    
            string[] values = nvc.GetValues(key);
            if (values == null) continue;
    
            foreach (string value in values)
            {
                sb.Append(sb.Length == 0 ? "?" : "&");
                sb.AppendFormat("{0}={1}", Uri.EscapeDataString(key), Uri.EscapeDataString(value));
            }
        }
    
        return sb.ToString();
    }
    

    Example

    var queryParams = new NameValueCollection()
    {
        { "order_id", "0000" },
        { "item_id", "1111" },
        { "item_id", "2222" },
        { null, "skip entry with null key" },
        { "needs escaping", "special chars ? = &" },
        { "skip entry with null value", null }
    };
    
    Console.WriteLine(queryParams.ToQueryString());
    

    Output

    ?order_id=0000&item_id=1111&item_id=2222&needs%20escaping=special%20chars%20%3F%20%3D%20%26
    

提交回复
热议问题