首页 > 解决方案 > 无法使用 Apollo Client 和 GraphQL .NET 将值转换为 AST

问题描述

当我在 React 中使用 Apollo Client 调用 .NET GraphQL 后端时,我遇到了一个奇怪的问题。

由于某些未知原因,我的字符串类型出现以下错误:

Cannot convert value to AST

如果我使用fetchaxios发布查询和突变,我的后端工作正常,但这个错误只发生在 Apollo 上。

由于 Apollo,我不得不将我的变量类型更改为Inputs而不是JObject,并且错误开始发生。

这是我的新 GraphQL 请求类:

using GraphQL;

namespace xyz.com
{
    public class GraphQLQuery
    {
        public string OperationName { get; set; }
        public string NamedQuery { get; set; }
        public string Query { get; set; }
        public Inputs Variables { get; set; }
    }
}

不过以前是这样的:

public class GraphQLQuery
        {
            public string OperationName { get; set; }
            public string NamedQuery { get; set; }
            public string Query { get; set; }
            public JObject Variables { get; set; }
        }

如果我使用 JObject,我会在我的 post 方法中通过 Apollo 调用获得一个空对象。

标签: .netgraphqlapollo-client

解决方案


好的。几个小时后,我想出了如何解决这个问题。

这就是我所做的。

我将 API 方法参数更改为以下内容:

public async Task<IActionResult> Post([FromBody] System.Text.Json.JsonElement rawQuery)

然后我添加了以下行以将 rawQuery 值反序列化到 GraphQL 请求对象:

var graphQLQuery = JsonConvert.DeserializeObject<GraphQLQuery>(rawQuery.ToString());

现在代码完美运行。


推荐阅读