【问题标题】:Add content-type header while consuming API using GraphQL.client在使用 GraphQL.client 使用 API 时添加内容类型标头
【发布时间】:2020-12-10 07:19:42
【问题描述】:

我正在使用 GraphQL.client Nuget 包来调用需要 Content-Type 标头的 Graphql API。 以下是我正在做的事情

设置 GraphQL 选项。注意我已经设置了 options.MediaType

GraphQLHttpClientOptions options = new GraphQLHttpClientOptions();
options.MediaType = "application/json";
options.EndPoint = new Uri( "https://sample.api.com/graphql");
        

初始化客户端和授权头

var graphQLClient = new GraphQLHttpClient(options, new NewtonsoftJsonSerializer());         
graphQLClient.HttpClient.DefaultRequestHeaders.Add("Authorization", "JWT <token>");
        

GraphQL 查询

var projectsQuery = new GraphQLRequest
{
  Query = @"
    query {
      projects {
        name
      }
    }"
};          

调用 API 并检索响应结果

var graphQLResponse = await graphQLClient.SendQueryAsync<ProjectResponse>(projectsQuery);            
var projects = graphQLResponse.Data.Projects;

但是我收到错误请求,错误为 "{"errors":[{"message":"Must provide query string."}]}"

我在这里做错了什么?如何正确设置内容类型标头。我尝试如下添加内容类型标头,但它不允许提供

错误的标题名称。确保请求标头与 HttpRequestMessage,带有 HttpResponseMessage 的响应标头,以及 带有 HttpContent 对象的内容标头。

graphQLClient.HttpClient.DefaultRequestHeaders.Add("content-type", "application/json");

我尝试寻找解决方案,但没有找到。当我通过 Postman 客户端在请求标头中传递内容类型标头时,相同的请求有效。

有没有人指点一下?

【问题讨论】:

    标签: c# graphql


    【解决方案1】:

    如果有人还在寻找答案,请在下面找到。

    var graphQLClient = new graphQLHttpClient("https://www.example.com/graphql", new NewtonsoftJsonSerializer());
    graphQLClient.HttpClient.DefaultRequestHeaders.Add("key", "value");
    

    请注意graphQLClient中的HttpClientHttpClient.DefaultRequestHeaders.Add("key", "value");

    【讨论】:

      猜你喜欢
      • 2018-04-09
      • 2014-04-22
      • 1970-01-01
      • 2018-07-22
      • 2016-01-01
      • 2019-02-24
      • 2022-01-12
      • 2013-09-09
      • 1970-01-01
      相关资源
      最近更新 更多