Search code examples
asp.netparametershttpwebrequestrequestwebrequest

Is there a URL builder that supports request parameter concatenation as well?


I want to achieve something like the following:

UrlBuilder ub = new UrlBuilder("http://www.google.com/search");
ub.Parameters.Add("q","request");
ub.Parameters.Add("sourceid","ie8");

string uri = ub.ToString(); //http://www.google.com/search?q=request&sourceid=ie8

Is there anything in .NET, or I will have to create my own?


Solution

  • Nothing exists that I know of. Here's something simple which does what you want. Usage would be:

            UrlBuilder ub = new UrlBuilder("www.google.com/search")
            .AddQuery("q", "request")
            .AddQuery("sourceid", "ie8");
    
            string url=ub.ToString();
    

    ==

    Code is:

        public class UrlBuilder
        {
            private string _authority;
            private string _host;
            private int? _port;
            private Dictionary<string, object> _query = new Dictionary<string, object>();
    
            public UrlBuilder(string host)
                : this("http", host, null)
            {
    
            }
            public UrlBuilder(string authority, string host)
                : this(authority, host, null)
            {
            }
            public UrlBuilder(string authority, string host, int? port)
            {
                this._authority = authority;
                this._host = host;
                this._port = port;
            }
    
            public UrlBuilder AddQuery(string key, object value)
            {
                this._query.Add(key, value);
                return this;
            }
    
            public override string ToString()
            {
                string url = _authority + "://" + _host;
                if (_port.HasValue)
                {
                    url += ":" + _port.ToString();
                }
    
    
                return AppendQuery(url);
            }
    
            private string AppendQuery(string url)
            {
                if (_query.Count == 0)
                {
                    return url;
                }
    
                url += "?";
                bool isNotFirst = false;
                foreach (var key in this._query.Keys)
                {
                    if (isNotFirst)
                    {
                        url += "&";
                    }
                    url += HttpUtility.UrlEncode(key) + "=" + HttpUtility.UrlEncode(this._query[key].ToString());
                    isNotFirst = true;
                }
    
                return url;
            }
        }
    }