如何在C#中的GraphQL Client端点的请求主体中发送oauth_token和client_id

时间:2018-06-29 11:05:04

标签: c# graphql graphql-dotnet

我想在GraphQL客户端的请求正文中传递oauth_tokenclient_id的朋友。那么我该如何传递它们,因为GraphQLRequest只有三个字段(即Query,Variables和OperationName)。请提出建议。

using GraphQL.Client;

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

var  graphQLResponse = await graphQLClient.PostAsync(heroRequest);

2 个答案:

答案 0 :(得分:1)

您可以使用 GraphQLClient 中的 DefaultRequestHeaders 授权(或任何其他参数)添加到标题中。

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);

在这里您可以从HttpClient中找到有关DefaultRequestHeaders的更多详细信息: Setting Authorization Header of HttpClient

此外,在graphql-dotnet git上创建了一个相关问题。
https://github.com/graphql-dotnet/graphql-client/issues/32

答案 1 :(得分:0)

使用 GraphQLHttpClient 而不是 GraphQLClient

示例:

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{......}"
        }
        ...
    }
}

当然,您必须在启动注册您的 GraphQLHttpClient。

示例:

services.AddScoped(s => new GraphQLHttpClient(Configuration["YourGraphQLUri", new NewtonsoftJsonSerializer()));