Append values to query string

后端 未结 8 1474
借酒劲吻你
借酒劲吻你 2020-11-28 20:32

I have set of URL\'s similar to the ones below in a list

  • http://somesite.com/backup/lol.php?id=1&server=4&location=us
  • http://somesite.com/news
8条回答
  •  庸人自扰
    2020-11-28 21:01

    I've wrapped Darin's answer into a nicely reusable extension method.

    public static class UriExtensions
    {
        /// 
        /// Adds the specified parameter to the Query String.
        /// 
        /// 
        /// Name of the parameter to add.
        /// Value for the parameter to add.
        /// Url with added parameter.
        public static Uri AddParameter(this Uri url, string paramName, string paramValue)
        {
            var uriBuilder = new UriBuilder(url);
            var query = HttpUtility.ParseQueryString(uriBuilder.Query);
            query[paramName] = paramValue;
            uriBuilder.Query = query.ToString();
    
            return uriBuilder.Uri;
        }
    }
    

    I hope this helps!

提交回复
热议问题