[英]HttpClient- adding parameters to Get request
I have a RestRequest which I am trying to convert to HttpClient Get request. 我有一个RestRequest,我试图转换为HttpClient获取请求。 Is there any way I can send parameters the way it is done below?
有什么方法可以按照下面的方式发送参数吗?
private readonly IRestClient _restClient;
public Type GetInfo(string name)
{
var request = new RestRequest(url, Method.GET);
request.AddParameter("name", "ivar");
var response = _restClient.ExecuteRequest(request);
return ExecuteRequest<Type>(request);
}
If I recall correctly, RestSharp's AddParameter
method doesn't add request headers but rather add Uri arguments for GET or request body parameters for POST. 如果我没记错的话,RestSharp的
AddParameter
方法不会添加请求标头,而是为GET添加Uri参数或为POST请求体参数。
There is no analogous method for HttpClient
so you need to format the Uri for a GET request yourself. HttpClient
没有类似的方法,因此您需要自己格式化Uri以获取GET请求。
Here's a method I find handy that will take a dictionary of string/object pairs and format a Uri query string. 这是一个方便的方法,它将采用字符串/对象字典并格式化Uri查询字符串。
public static string AsQueryString(this IEnumerable<KeyValuePair<string, object>> parameters)
{
if (!parameters.Any())
return "";
var builder = new StringBuilder("?");
var separator = "";
foreach (var kvp in parameters.Where(kvp => kvp.Value != null))
{
builder.AppendFormat("{0}{1}={2}", separator, WebUtility.UrlEncode(kvp.Key), WebUtility.UrlEncode(kvp.Value.ToString()));
separator = "&";
}
return builder.ToString();
}
In the line where you are calling Request.AddParameter(name, value)
, change that instead to Request.AddQueryParameter(name, value)
. 在您调用
Request.AddParameter(name, value)
,将其更改为Request.AddQueryParameter(name, value)
。 For GETs this is the preferred approach and puts the parameters you specify into a querystring. 对于GET,这是首选方法,并将您指定的参数放入查询字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.