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

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

    I answered a similar question a while ago. Basically, the best way would be to use the class HttpValueCollection, which ASP.NET's Request.QueryString property actually is, unfortunately it is internal in the .NET framework. You could use Reflector to grab it (and place it into your Utils class). This way you could manipulate the query string like a NameValueCollection, but with all the url encoding/decoding issues taken care for you.

    HttpValueCollection extends NameValueCollection, and has a constructor that takes an encoded query string (ampersands and question marks included), and it overrides a ToString() method to later rebuild the query string from the underlying collection.

    Example:

      var coll = new HttpValueCollection();
    
      coll["userId"] = "50";
      coll["paramA"] = "A";
      coll["paramB"] = "B";      
    
      string query = coll.ToString(true); // true means use urlencode
    
      Console.WriteLine(query); // prints: userId=50¶mA=A¶mB=B
    

提交回复
热议问题