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

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

    In dotnet core QueryHelpers.AddQueryString() will accept an IDictionary of key-value pairs. To save a few memory allocs and CPU cycles you can use SortedList<,> instead of IDictionary<,>, with an appropriate capacity and items added in sort order...

    var queryParams = new SortedList(2);
    queryParams.Add("abc", "val1");
    queryParams.Add("def", "val2");
    
    string requestUri = QueryHelpers.AddQueryString("https://localhost/api", queryParams);
    

提交回复
热议问题