1

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".

2
  • Why don't you pass a Dictionary to your function? Commented Mar 2, 2017 at 4:31
  • I tried to do it but when we call it from every method it might be hactic to create dictionary objcet all time. Can we do something using params obejct[] . I tried but didn't get any way to get actual parameter name which we pass from calling method Commented Mar 2, 2017 at 4:38

1 Answer 1

1

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);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I tried params but as i need to key value pair from that. Value can be easily fetched but how would i get actual parameter name

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.