C# 使用 RestSharp 向 POST 请求添加 GET 参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10747261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 15:05:06  来源:igfitidea点击:

Add a GET parameter to a POST request with RestSharp

c#.netweb-serviceswebservice-clientrestsharp

提问by leninyee

I want to make a POST request to a URL like this:

我想向这样的 URL 发出 POST 请求:

http://localhost/resource?auth_token=1234

And I want to send JSON in the body. My code looks something like this:

我想在正文中发送 JSON。我的代码看起来像这样:

var client = new RestClient("http://localhost");
var request = new RestRequest("resource", Method.POST);
request.AddParameter("auth_token", "1234");    
request.AddBody(json);
var response = client.Execute(request);

How can I set the auth_tokenparameter to be a GET parameter and make the request as POST?

如何将auth_token参数设置为 GET 参数并将请求设为 POST?

采纳答案by Ender2050

This should work if you 1) add the token to the resource url and 2) specify ParameterType.UrlSegment like this:

如果您 1) 将令牌添加到资源 url 并且 2) 像这样指定 ParameterType.UrlSegment,这应该可以工作:

var client = new RestClient("http://localhost");
var request = new RestRequest("resource?auth_token={authToken}", Method.POST);
request.AddParameter("auth_token", "1234", ParameterType.UrlSegment);    
request.AddBody(json);
var response = client.Execute(request);

This is far from ideal - but the simplest way I've found... still hoping to find a better way.

这远非理想 - 但我找到的最简单的方法......仍然希望找到更好的方法。

回答by Der_Meister

The current version of RestSharp has a short method that makes use of a template:

当前版本的 RestSharp 有一个使用模板的简短方法:

var request = new RestRequest("resource?auth_token={token}", Method.POST);
request.AddUrlSegment("token", "1234");

Alternatively, you can add a parameter without a template:

或者,您可以添加一个没有模板的参数:

var request = new RestRequest("resource", Method.POST);
request.AddQueryParameter("auth_token", "1234); 

or

或者

var request = new RestRequest("resource", Method.POST);
request.AddParameter("auth_token", "1234", ParameterType.QueryString);