0

你好朋友,我想通过oauth_tokenclient_id进入 GraphQL 客户端的请求正文。那么我该如何传递它们,因为 GraphQLRequest 只有三个字段(即 Query、Variables 和 OperationName)。请建议。

using GraphQL.Client;

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

var  graphQLResponse = await graphQLClient.PostAsync(heroRequest);
4

2 回答 2

4

您可以使用来自GraphQLClient的DefaultRequestHeaders将Authorization(或任何其他参数)添加到 Header 。

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 的更多详细信息: 设置 HttpClient 的授权标头

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

于 2018-10-15T08:13:12.143 回答
2

使用 GraphQL Http客户端而不是 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{......}"
        }
        ...
    }
}

当然,您必须在Startup中注册您的 GraphQLHttpClient 。

例子:

services.AddScoped(s => new GraphQLHttpClient(Configuration["YourGraphQLUri", new NewtonsoftJsonSerializer()));
于 2021-08-11T12:51:41.357 回答