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

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

    Assuming that you want to reduce dependencies to other assemblies and to keep things simple, you can do:

    var sb = new System.Text.StringBuilder();
    
    sb.Append("a=" + HttpUtility.UrlEncode("TheValueOfA") + "&");
    sb.Append("b=" + HttpUtility.UrlEncode("TheValueOfB") + "&");
    sb.Append("c=" + HttpUtility.UrlEncode("TheValueOfC") + "&");
    sb.Append("d=" + HttpUtility.UrlEncode("TheValueOfD") + "&");
    
    sb.Remove(sb.Length-1, 1); // Remove the final '&'
    
    string result = sb.ToString();
    

    This works well with loops too. The final ampersand removal needs to go outside of the loop.

    Note that the concatenation operator is used to improve readability. The cost of using it compared to the cost of using a StringBuilder is minimal (I think Jeff Atwood posted something on this topic).

提交回复
热议问题