Add a GET parameter to a POST request with RestSharp

一曲冷凌霜 提交于 2019-12-20 12:27:02

问题


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

http://localhost/resource?auth_token=1234

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

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_token parameter to be a GET parameter and make the request as POST?


回答1:


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

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.




回答2:


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

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); 


来源:https://stackoverflow.com/questions/10747261/add-a-get-parameter-to-a-post-request-with-restsharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!