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

前端 未结 30 2538
借酒劲吻你
借酒劲吻你 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:31

    While not elegant, I opted for a simpler version that doesn't use NameValueCollecitons - just a builder pattern wrapped around StringBuilder.

    public class UrlBuilder
    {
        #region Variables / Properties
    
        private readonly StringBuilder _builder;
    
        #endregion Variables / Properties
    
        #region Constructor
    
        public UrlBuilder(string urlBase)
        {
            _builder = new StringBuilder(urlBase);
        }
    
        #endregion Constructor
    
        #region Methods
    
        public UrlBuilder AppendParameter(string paramName, string value)
        {
            if (_builder.ToString().Contains("?"))
                _builder.Append("&");
            else
                _builder.Append("?");
    
            _builder.Append(HttpUtility.UrlEncode(paramName));
            _builder.Append("=");
            _builder.Append(HttpUtility.UrlEncode(value));
    
            return this;
        }
    
        public override string ToString()
        {
            return _builder.ToString();
        }
    
        #endregion Methods
    }
    

    Per existing answers, I made sure to use HttpUtility.UrlEncode calls. It's used like so:

    string url = new UrlBuilder("http://www.somedomain.com/")
                 .AppendParameter("a", "true")
                 .AppendParameter("b", "muffin")
                 .AppendParameter("c", "muffin button")
                 .ToString();
    // Result: http://www.somedomain.com?a=true&b=muffin&c=muffin%20button
    

提交回复
热议问题