Reputation: 87
I am working on a solution where i need to call web api in other web api. Both api is hosted on different server. So i found a generic solution to call Web api as given below but i am not getting any way to find generic solution for parameters.
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);
}
}
Can someone please help on this so if i pass any number of parameters then it should make it key value pair as you can see in parameter "top".
Upvotes: 1
Views: 1062
Reputation: 4895
I think what you're looking for is params
keyword in C#
It allows you to pass in n
number of parameters
Your code will look like this
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);
}
}
Upvotes: 1