是否可以使用.NET core中的标准httpclient发送graphQL查询? 当我尝试使用 client.post 发送查询时,我得到
"Expected { or [ as first syntax token."
如何使用 httpclient 发送 GraphQL 查询。 无需使用库(如 GraphQLHttpClient 等)
以下是如何在 .net Core 中使用 HttpClient 调用 GraphQL 端点的示例:
public async Task<string> GetProductsData(string userId, string authToken)
{
var httpClient = new HttpClient
{
BaseAddress = new Uri(_apiUrl)
};
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
var queryObject = new
{
query = @"query Products {
products {
id
description
title
}
}",
variables = new { where = new { userId = userId } }// you can add your where clause here.
};
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
Content = new StringContent(JsonConvert.SerializeObject(queryObject), Encoding.UTF8, "application/json")
};
using (var response = await httpClient.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var responseString = await response.Content.ReadAsStringAsync();
return responseString;
}
}
明白了: 只需添加“query”作为 json 对象即可。像这样:
{"query" : "query { __schema { queryType { name } mutationType { name } types { name } directives { name } } }"}
在 .NET 中,您可以在 HTTP post 中使用它(不要忘记对双引号进行字符串转义
private static string myquery = "{ \"query\" : \"query { __schema { queryType { name } mutationType { name } types { name } directives { name } } }\" }";