mardi 2 juin 2020

How to properly set my IRestRequest request in my generic SendRequest to avoid System.NullReferenceException?

I have created a generic SendRequest method which will use the token and if I have any query parameters it will add it and send the request. But I need help on how to property set the IRestRequest request its throwing the System.NullReferenceException due to the request being null. if I do not set it to any anything it gives me an error..Use of Unassigned local variable "request".

//Here is the method

 private static IRestRequest SendRequest(string token, Dictionary<string,string> queryParams)
        {
           IRestRequest request; //THIS IS THE LINE WHERE I AM FACING THE PROBLEM

            //if token is null no need to add the token. Some request requires token, Some does not
            if (token != null)
            {
                request.AddParameter("Authorization", "Bearer" + token, ParameterType.QueryString);
            }


            //Adding JSON content type as all APIs accept it. 
            request.AddHeader("Accept", "application/json");


            foreach(var param in queryParams)
            {
                request.AddQueryParameter(param.Key, param.Value);
            }

            return request;
        }

//Here is my get method

   public static IRestResponse doGet(string baseURL, string basePath, IRestClient client,
            string token, Dictionary<string, string> paramsMap)
        {
            if (setBaseURI(baseURL)) //if this is true it will send the request
            {
                IRestRequest request = SendRequest(token, paramsMap);
                return getResponse("GET", request, client, basePath);
            }
            return null;

        }

//Here is how I am using in the Test class

 [Test]
        public void GetUserById()
        {
            IRestResponse response = BaseServiceCall.doGet(baseUrl, "GetUserById", client, token, null);
            int statusCode = (int)response.StatusCode;
            Assert.AreEqual(response.StatusCode, statusCode);
        }

Aucun commentaire:

Enregistrer un commentaire