0

我想使用 Web 服务或处理程序将突变发送到 GraphQL API。我有 GraphQL 代码在 Postman 和一个控制台应用程序中工作。但是每当我在服务或处理程序中尝试类似的代码时,我所能得到的只是一个 400 错误请求。目前正在尝试使用 HttpTaskAsyncHandler:

public class AsyncHandler : HttpTaskAsyncHandler {

    public override async Task ProcessRequestAsync (HttpContext context) {
        context.Response.ContentType = "text/plain";
        string result = await GoSC();
        context.Response.Write(result);
    }

    public async Task<string> GoSC()
    {
        // Define the cancellation token.
        CancellationTokenSource source = new CancellationTokenSource();
        CancellationToken cancellationToken = source.Token;

        HttpClient client = new HttpClient();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "*******");
        client.DefaultRequestHeaders.Add("User-Agent", "MyApp");

        string uri = "https://theAPI.com/graphql";

        using (var request = new HttpRequestMessage(HttpMethod.Post, uri))
        {
            var queryObject = new
            {
                query = @"query {query{currentOrgId}}"
            };            

            using (var stringContent = new StringContent(
                                            JsonConvert.SerializeObject(queryObject),
                                            System.Text.Encoding.UTF8,
                                            "application/json"))
            {
                request.Content = stringContent;

                using (var response = await client
                    .SendAsync(request,
                            HttpCompletionOption.ResponseContentRead,
                            cancellationToken)
                    .ConfigureAwait(false))
                {
                    response.EnsureSuccessStatusCode();
                    //string resString = response.StatusCode.ToString();
                    string resString = await response.Content.ReadAsStringAsync();
                    //string resString = await response.Content
                    return resString;
                }
            }
        }
    }

我已经尝试了从直接字符串到序列化 Json 的所有 HttpRequestMessage 内容。总是错误的请求。任何智慧之言将不胜感激!杰瑞

4

1 回答 1

0

原来我们在 Web 服务器上运行了一个 http 到 https 的重定向,它以某种方式干扰了 API。需要将处理程序移到我自己的电脑上才能弄清楚。

于 2021-12-16T19:53:40.730 回答