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

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

    I needed to solve the same problem for a portable class library (PCL) that I'm working on. In this case, I don't have access to System.Web so I can't use ParseQueryString.

    Instead I used System.Net.Http.FormUrlEncodedContent like so:

    var url = new UriBuilder("http://example.com");
    
    url.Query = new FormUrlEncodedContent(new Dictionary()
    {
        {"param1", "val1"},
        {"param2", "val2"},
        {"param3", "val3"},
    }).ReadAsStringAsync().Result;
    

提交回复
热议问题