制作参数的通用列表使用HTTPClient调用Web API时

时间:2017-03-02 04:19:21

标签: c# asp.net-web-api httpclient

我正在开发一个解决方案,我需要在其他网络API中调用web api。两个api都托管在不同的服务器上。所以我找到了一个通用的解决方案来调用Web api,如下所示,但我没有找到任何方法来找到参数的通用解决方案。

public T Get<t>(int top = 0, int skip = 0)
{
    using (var httpClient = new HttpClient())
    {
        var endpoint = _endpoint + "?";
        var parameters = new List<string>();

        if (top > 0)
            parameters.Add(string.Concat("$top=", top));

        if (skip > 0)
            parameters.Add(string.Concat("$skip=", skip));

        endpoint += string.Join("&", parameters);

        var response = httpClient.GetAsync(endpoint).Result;

        return JsonConvert.DeserializeObject<t>(response.Content.ReadAsStringAsync().Result);
    }
}

有人可以帮忙解决这个问题,所以如果我传递任意数量的参数,那么它应该使它成为键值对,你可以在参数&#34; top&#34;中看到。

1 个答案:

答案 0 :(得分:1)

我认为您所寻找的是params

中的C#关键字

它允许您传递n个参数

您的代码将如下所示

public T Get<t>(params KeyValuePair<string, string>[] kvps)
{
    using (var httpClient = new HttpClient())
    {
        var url = !kvps.Any() ? _endpoint : $"{_endpoint}?{string.Join("&$", kvps.Select(kvp => string.Format("{0}={1}", kvp.Key, kvp.Value)))}";
        var response = httpClient.GetAsync(url).Result;
        return JsonConvert.DeserializeObject<t>(response.Content.ReadAsStringAsync().Result);
    }
}