Search code examples
c#getasp.net-core-webapirestsharprest-client

c# .Net core RestSharp RestRequest hot to call GET API with query parameters of different type - int and string


This is the API URL I need to call - "https://localhost:300/api/vi/Product?center=10&ProdNumber=271"

It has 2 quey parameters, center is of type string and ProdNumber is of type int

Now when I am trying to call this endpoint using generalized code for Get endpoint, since I have parameters of different type, not sure how to form the request object, to have both the parameters with values.

Please find my code below, please guide

 public RestRequest RestRequestGet<T>(string uri, List<RequestParameterVM> parameter)
    {
        var request = new RestRequest(uri, Method.Get);
        request.AddHeader("content-type", "application/json");
        parameter.ForEach(param =>
            request.AddParameter(param.ParameterKey, param.ParameterValue));
        return request;
    }

 public class RequestParameterVM
    {
        public string ParameterKey { get; set; } = null!;
        public string ParameterValue { get; set; } = null!;
    }

// Calling the Get endpoint 

List<RequestParameterVM> requestParameter= new List<RequestParameterVM>();
string url = $"{_configuration[Keys.url]}";

//requestParameter-- not sure how to form both the query parameters here to pass in the below method

 var restClient = new RestClient();
var request = _service.RestRequestGet<List<RequestParameterVM>>(url, requestParameter);
RestResponse response = await restClient.ExecuteAsync(request);
if (response.Content != null)
  return JsonConvert.DeserializeObject<order>(response.Content) 

Solution

  • If you want send Get Request with RestClient,you shouldn't add parameters to the request body

    request.AddHeader("content-type", "application/json");
    parameter.ForEach(param =>
          request.AddParameter(param.ParameterKey, param.ParameterValue));
    

    You could pass the value with query,try constrcut the uri as below:

    foreach(var key in dic.Keys)
                {
                    uribuiler.Query += string.Format("{0}={1}&", key, dic[key]);
                }
                uribuiler.Query.TrimEnd('&');
                var uri = uribuiler.Uri;