How to build a query string for a URL in C#?

前端 未结 30 2508
借酒劲吻你
借酒劲吻你 2020-11-22 01:55

A common task when calling web resources from a code is building a query string to including all the necessary parameters. While by all means no rocket science, there are so

30条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 02:36

    Add this class to your project

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    public class QueryStringBuilder
    {
        private readonly List> _list;
    
        public QueryStringBuilder()
        {
            _list = new List>();
        }
    
        public void Add(string name, object value)
        {
            _list.Add(new KeyValuePair(name, value));
        }
    
        public override string ToString()
        {
            return String.Join("&", _list.Select(kvp => String.Concat(Uri.EscapeDataString(kvp.Key), "=", Uri.EscapeDataString(kvp.Value.ToString()))));
        }
    }
    

    And use it like this:

    var actual = new QueryStringBuilder {
        {"foo", 123},
        {"bar", "val31"},
        {"bar", "val32"}
    };
    
    actual.Add("a+b", "c+d");
    
    actual.ToString(); // "foo=123&bar=val31&bar=val32&a%2bb=c%2bd"
    

提交回复
热议问题