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

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

    My offering:

    public static Uri AddQuery(this Uri uri, string name, string value)
    {
        // this actually returns HttpValueCollection : NameValueCollection
        // which uses unicode compliant encoding on ToString()
        var query = HttpUtility.ParseQueryString(uri.Query);
    
        query.Add(name, value);
    
        var uriBuilder = new UriBuilder(uri)
        {
            Query = query.ToString()
        };
    
        return uriBuilder.Uri;
    }
    

    Usage:

    var uri = new Uri("http://stackoverflow.com").AddQuery("such", "method")
                                                 .AddQuery("wow", "soFluent");
    
    // http://stackoverflow.com?such=method&wow=soFluent
    

提交回复
热议问题