Search code examples
c#restsharp

RestSharp Response Content Always Null But Still Logs With Execute


When sending a basic GET the response.Content is always NULL on return. The weird thing is that it will log the content on the standard execute, but not on the async. I'm at my wit's end. Any help would be appreciated.

I tried using the standard client.Execute and client.ExecuteAsync and both seem to have the same result, except for the logging part.

The regular method (with identifying info X'd out):

                RestClient myClient = new RestClient(uri);
                var request = new RestRequest(Method.GET);

                request.AddHeader("cache-control", "no-cache");
                request.AddHeader("Connection", "keep-alive");
                request.AddHeader("accept-encoding", "gzip, deflate");
                request.AddHeader("Host", "XXXXX");
                request.AddHeader("Cache-Control", "no-cache");
                request.AddHeader("Accept", "*/*");
                request.AddHeader("Authorization", "XXX");

                Serilog.Log.Information($"Request is {request}");

                IRestResponse response = myClient.Execute(request);
                var htmlString = response.Content;
                Serilog.Log.Information($"Request is {response.Content}");

                return htmlString;

The executeAsync method:

                RestClient myClient = new RestClient(uri);
                var request = new RestRequest(Method.GET);

                request.AddHeader("cache-control", "no-cache");
                request.AddHeader("Connection", "keep-alive");
                request.AddHeader("accept-encoding", "gzip, deflate");
                request.AddHeader("Host", "XXXXX");
                request.AddHeader("Cache-Control", "no-cache");
                request.AddHeader("Accept", "*/*");
                request.AddHeader("Authorization", "XXXXXXXXXX");

                Serilog.Log.Information($"Request is {request}");
                var htmlString = "";
                myClient.ExecuteAsync(request, response =>
                {
                    htmlString = response.Content;
                    Serilog.Log.Information($"Response is {response.Content}");
                });
                return htmlString;

Obviously I want it to both log AND return the actual content. Ok, gurus, what am I doing wrong?


Solution

  • You have to be kidding me. It was working all the time (at least the regular execute), but there was so much whitespace at the beginning of the string that VS 2017 didn't display it as a local. I had to really drill down to see it.