如何解决C#环境下GraphiQL查询参数默认值与配置不符问题
问题根因
你遇到的问题是GraphQL规范和GraphiQL Explorer的默认行为共同导致的:
- 按照GraphQL官方规范,标记为
NonNullGraphType的参数不支持设置默认值,你在代码中给NonNull类型参数配置的DefaultValue = 100000不会被写入返回给前端的Schema中,GraphiQL无法识别到这个配置值。 - GraphiQL Explorer对于Int类型的必填参数,会自动填充默认示例值
10,这就是你看到的异常值来源。
解决方案
方案1:保留参数默认值(推荐)
如果参数允许用户不传、使用默认值,说明该参数本质是可选的,去掉NonNullGraphType约束即可,修改后的代码如下:
FieldAsync<ListGraphType<PartitionedCountGraphType>>("partitionedCounts", description: "Returns counts of the meter reads partitioned by ranges of id values..", arguments: new QueryArguments( new QueryArgument<IntGraphType> // 去掉NonNullGraphType包装 { Name = "partitionInterval", DefaultValue = 100000, Description = "Specifies the size of group that the meter reads should be divided into (e.g. 100000)." }), resolve: async context => { return await GetPartitionedCountsAsync(context); });
修改后Schema会正确暴露默认值,GraphiQL构建查询时会自动填充100000作为参数值。
方案2:强制参数必填,关闭GraphiQL自动填充
如果你的业务要求该参数必须由用户手动传入,不需要默认值,可以做两处修改:
- 删掉参数配置中的
DefaultValue = 100000代码,保留NonNullGraphType约束。 - 在.NET Core的Startup.cs/Program.cs中配置GraphiQL时,关闭Explorer自动填充变量的功能,配置示例如下:
app.UseGraphiQLServer(new GraphiQLOptions { ExplorerSettings = new Dictionary<string, object> { ["autoFillVariables"] = false } });
配置后GraphiQL Explorer构建查询时不会自动填充任何默认参数值,会留空让用户手动输入。
内容的提问来源于stack exchange,提问作者Tony
相关产品推荐
相关产品推荐

