简体   繁体   中英

HttpClient- adding parameters to Get request

I have a RestRequest which I am trying to convert to HttpClient Get request. 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.

There is no analogous method for HttpClient so you need to format the Uri for a GET request yourself.

Here's a method I find handy that will take a dictionary of string/object pairs and format a Uri query string.

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) . For GETs this is the preferred approach and puts the parameters you specify into a querystring.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM