3

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
  • 1,633
  • 1
  • 22
  • 37
Aryan
  • 31
  • 1
  • 4

3 Answers3

5

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

Tiago Máximo
  • 51
  • 1
  • 6
  • 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
  • 1
    var graphQLClient = new GraphQLHttpClient("http://localhost/graphql", new NewtonsoftJsonSerializer()); graphQLClient.HttpClient.DefaultRequestHeaders.Add("Authorization", "Bearer ????"); – Robin Qiu Oct 17 '22 at 05:08
4

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
  • 1,177
  • 1
  • 13
  • 37
0
var graphQLClient = new GraphQLHttpClient("localhost/graphql", new NewtonsoftJsonSerializer()); 
graphQLClient.HttpClient.DefaultRequestHeaders.Add("Authorization", "Bearer ????");
Robin Qiu
  • 5,521
  • 1
  • 22
  • 19