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

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

    Same as accepted solution, but transfred to "dot" LINQ syntax...

    private string ToQueryString(NameValueCollection nvc)
    {
        if (nvc == null) return String.Empty;
        var queryParams = 
              string.Join("&", nvc.AllKeys.Select(key => 
                  string.Join("&", nvc.GetValues(key).Select(v => string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(v))))));
        return "?" + queryParams;
    }
    

提交回复
热议问题