0

Hello friends I want pass oauth_token and client_id in request body of a GraphQL Client. So how can I pass them, because GraphQLRequest has only three fields (i.e Query , Variables and OperationName). Please suggest.

using GraphQL.Client;

var heroRequest = new GraphQLRequest{ Query = Query };
var graphQLClient = new GraphQLClient("URL");

var  graphQLResponse = await graphQLClient.PostAsync(heroRequest);
Kevin Woblick
  • 1,440
  • 1
  • 20
  • 33
Aryan
  • 1
  • 1
  • 3

2 Answers2

4

You can add the Authorization (or any other parameter) to the Header using the DefaultRequestHeaders from GraphQLClient.

var graphClient = new GraphQLClient("https://api.github.com/graphql");
graphClient.DefaultRequestHeaders.Add("Authorization", $"bearer {ApiKey}");

var request = new GraphQLRequest
{
    Query = @"query { viewer { login } }"
};

var test = await graphClient.PostAsync(request);

Here you can find more detailed information about the DefaultRequestHeaders from HttpClient: Setting Authorization Header of HttpClient

Also, there's a related issue created on graphql-dotnet git.
https://github.com/graphql-dotnet/graphql-client/issues/32

  • 1
    If your GraphQLClient is the one from https://github.com/graphql-dotnet/graphql-client , then GraphQLClient class does not have definition for DefaultRequestHeaders. – Daming Fu Mar 10 '21 at 05:33
  • Any answers how to add headers in https://github.com/graphql-dotnet/graphql-client ? – Adit Kothari Aug 03 '21 at 09:45
2

Use GraphQLHttpClient instead of GraphQLClient

example:

public class DemoController : Controller
{
    private readonly GraphQLHttpClient _client;
    
    public DemoController(GraphQLHttpClient client)
    {
        _client = client;
    }

    public async Task<ActionResult> YourMethod()
    {
        _client.HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("JWT", yourToken);
        var query = new GraphQLRequest
        {
            Query = "query{......}"
        }
        ...
    }
}

Of course you have to register your GraphQLHttpClient in Startup.

Example:

services.AddScoped(s => new GraphQLHttpClient(Configuration["YourGraphQLUri", new NewtonsoftJsonSerializer()));
Frederik Hoeft
  • 820
  • 1
  • 10
  • 27