1

I have GraphQL running on localhost (http://localhost:23061/graphql) and I'm trying to replicate the query I do in the UI directly but within C#. I have verified that the JSON package is correct on postman beforehand but whenever such package is attempted in C# it will just return a 500 error, I tried quite a few variations of this package (swapping " with ' as an example) but unfortunately all the same.

So the query I used on postman is {"query":"{goldBalance(address: "0xa49d64c31A2594e8Fb452238C9a03beFD1119963")}"} this returns just fine in postman.

When moving this to C# however;

    static async System.Threading.Tasks.Task Main(string[] args)
{
    var httpClient = new HttpClient();
    var url = "http://localhost:23061/graphql";
    var data = "{ \"query\":\"{goldBalance(address: \"0xa49d64c31A2594e8Fb452238C9a03beFD1119963\")}\"}";
    var content = new StringContent(data.ToString(), Encoding.UTF8, "application/json");
    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
    var result = httpClient.PostAsync(url, content).Result;


    Console.WriteLine(result);
}

When this is ran, it will always return;

StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
    {
      Date: Tue, 30 Mar 2021 20:18:36 GMT
      Server: Kestrel
      Content-Length: 0
    }

I thought initially that this could be a HTTPClient issue but WebRequest, so it is clearly an issue on my send somewhere.

Galio09
  • 31
  • 4

2 Answers2

2

Here is what I get using a similar request with Postman:

var client = new RestClient("http://localhost:23061/graphql");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Basic Og==");
request.AddHeader("Content-Type", "text/plain");
request.AddParameter("text/plain", "{\"query\":\"{goldBalance(address: \"0xa49d64c31A2594e8Fb452238C9a03beFD1119963\")}\"}",  ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

Try using this instead of the HttpClient.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Hanlet Escaño
  • 17,114
  • 8
  • 52
  • 75
1

Thanks to Hanlet, Postman has a code snippet section that literally has the solution. Appreciated.

I have also now figured out what the issue was, I didn't double escape around the address. Thanks.

Galio09
  • 31
  • 4
  • 2
    use JSONing tool instead of string hardcoding/manipulation ( https://stackoverflow.com/a/61882664/6124657 ), next step will be using variables https://graphql.org/learn/queries/#variables to make it dynamic – xadm Mar 30 '21 at 21:48
  • Thanks, this is actually what I was planning to try out tomorrow. – Galio09 Mar 30 '21 at 22:28
  • Could you share what your code looked like after the change? – Lee Whieldon Aug 22 '22 at 13:24