将 URL 查询字符串附加到请求

Append URL Query Strings to request

我正在尝试发送 POST 请求并将查询字符串格式化为特定格式。除了第一个参数外,顺序无关紧要,但我还没有成功。

我需要的:

localhost/someapp/api/dosomething/5335?save=false&userid=66462

我的一些尝试结果:

http://localhost/someapp/api/dosomething/?Id=29455&save=false&userId=797979 http://localhost/someapp/api/dosomething/?save=false&userId=797979

我如何格式化请求:

    request.AddQueryParameter("Id", "29455");
    request.AddQueryParameter("save", "false");
    request.AddQueryParameter("user", "4563533245");

如果我尝试 AddParameterfor Id 它不会附加到查询字符串上(我在想因为它是 POST 而不是 GET),所以不会工作。 API 期待的不是表格,而是 :

(string id, List<Dictionary<string,string>>)

我可以使用 StringBuilder,但感觉不对。我不确定 UrlSegment 是否是最好的方法,因为我基本上会破解查询字符串。有没有办法使用 RestSharp 的 API?

以我需要的格式来格式化我的请求

我最终使用的是 UrlSegment 然后保留了 .AddQueryParameter 方法,所以最终的代码块看起来像:

var url = new RestClient(localhost/someapp/api/dosomething/{id});
var request     = new RestRequest(Method.POST);

request.AddParameter("Id", "5335", ParameterType.UrlSegment);
request.AddQueryParameter("save", "true");
request.AddQueryParameter("UserId", "5355234");

它生成了我需要的 URI。

如果您不确定如何编码,使用 RestSharp 或任何其他 API 客户端库的最简单编码过程是使用 Postman 生成。下载 Postman,执行新请求,输入 URL 字符串以发送到 API,单击代码,从下拉列表中单击 select C# (RestSharp)。这是它生成的代码。

   var client = new RestClient("http://localhost/someapp/api/dosomething   /5335?save=false&userid=66462");
   var request = new RestRequest(Method.POST);
   request.AddHeader("Postman-Token", "bd05aa45-f1b9-4665-a3e7-888ad16f2800");  
   request.AddHeader("cache-control", "no-cache");
  IRestResponse response = client.Execute(request);