Append values to query string

后端 未结 8 1439
借酒劲吻你
借酒劲吻你 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
    {
        /// <summary>
        /// Adds the specified parameter to the Query String.
        /// </summary>
        /// <param name="url"></param>
        /// <param name="paramName">Name of the parameter to add.</param>
        /// <param name="paramValue">Value for the parameter to add.</param>
        /// <returns>Url with added parameter.</returns>
        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!

    0 讨论(0)
  • 2020-11-28 21:04

    You could use the HttpUtility.ParseQueryString method and an UriBuilder which provides a nice way to work with query string parameters without worrying about things like parsing, url encoding, ...:

    string longurl = "http://somesite.com/news.php?article=1&lang=en";
    var uriBuilder = new UriBuilder(longurl);
    var query = HttpUtility.ParseQueryString(uriBuilder.Query);
    query["action"] = "login1";
    query["attempts"] = "11";
    uriBuilder.Query = query.ToString();
    longurl = uriBuilder.ToString();
    // "http://somesite.com:80/news.php?article=1&lang=en&action=login1&attempts=11"
    
    0 讨论(0)
提交回复
热议问题