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

前端 未结 30 3027
借酒劲吻你
借酒劲吻你 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条回答
  •  暖寄归人
    2020-11-22 02:21

    Chain-able wrapper class for HttpValueCollection:

    namespace System.Web.Mvc {
        public class QueryStringBuilder {
            private NameValueCollection collection;
            public QueryStringBuilder() {
                collection = System.Web.HttpUtility.ParseQueryString(string.Empty);
            }
            public QueryStringBuilder Add(string key, string value) {
                collection.Add(key, value);
                return this;
            }
            public QueryStringBuilder Remove(string key) {
                collection.Remove(key);
                return this;
            }
            public string this[string key] {
                get { return collection[key]; }
                set { collection[key] = value; }
            }
            public string ToString() {
                return collection.ToString();
            }
        }
    }
    

    Example usage:

    QueryStringBuilder parameters = new QueryStringBuilder()
        .Add("view", ViewBag.PageView)
        .Add("page", ViewBag.PageNumber)
        .Add("size", ViewBag.PageSize);
    string queryString = parameters.ToString();
    

提交回复
热议问题