我开发了一个 .net core 3.1 web API,并添加了 GraphQL 和 游乐场到它。当我尝试启动 Playground 时,我遇到了这个让我感到厌烦的错误。我在谷歌上搜索了太多次,我已经阅读了很多关于它的文章和论坛,我已经尝试了他们建议的方法,但问题仍然存在。另外,我应该说我在 .net core 2.2 上没有这个问题。
我决定简化我的解决方案并删除我项目的额外叶子并将其上传给您,您可以帮助我。
我目前正在处理的那个项目的简化版本可用 here on google drive .
另外,我找到了一个没有这个问题的 .net core 3.1 解决方案,但仍然找不到我的错误。我已经上传了这个正确的解决方案 here .
在这个简化版本中,我没有连接到数据库,也没有将任何相关的包添加到项目中。我在这个简化版本中返回内存数据,而不是联系数据库。
这是我面临的错误的图片:
和 .csproj 简化项目的文件如下:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<RootNamespace>NetCore3._1GraphQL</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="graphiql" Version="1.2.0" />
<PackageReference Include="GraphQL" Version="3.0.0-preview-1352" />
<PackageReference Include="GraphQL.Server.Ui.Playground" Version="3.4.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.1" />
<PackageReference Include="RandomNameGeneratorLibrary" Version="1.2.2" />
</ItemGroup>
</Project>
最佳答案
根据简化和错误的项目,afaict,它配置了一个映射 /graphql
的路由。 Controller 的端点,但不包含匹配的 Controller 。因此,服务器返回 404 响应并且 graphql playground 产生错误消息。添加 Controller (或中间件)使其工作。
以下是使其工作的简化和错误项目的更改:
/graphql
路由。 // GraphqlController.cs
// using statements are omitted
namespace NetCore3._1GraphQL.Controllers
{
[ApiController]
[Route("[controller]")]
public class GraphqlController : ControllerBase
{
private readonly IServiceProvider _provider;
private readonly IDocumentExecuter _executer;
private readonly IDataLoaderContextAccessor _loader;
public GraphqlController(
IDocumentExecuter executer,
IServiceProvider provider,
IDataLoaderContextAccessor loader)
{
_executer = executer;
_provider = provider;
_loader = loader;
}
[HttpPost]
public async Task<IActionResult> Post([FromBody] GraphQLRequest graphQLRequest)
{
if (graphQLRequest == null)
{
throw new ArgumentNullException(nameof(graphQLRequest));
}
var _query = graphQLRequest.Query;
var _inputs = graphQLRequest.Variables?.ToObject<Inputs>();
var _options = new ExecutionOptions
{
Schema = new GraphQLSchema(_provider)
{
Query = new GraphQLQuery(_loader),
},
Query = _query,
Inputs = _inputs,
FieldNameConverter = new PascalCaseFieldNameConverter()
};
try
{
var result = await _executer.ExecuteAsync(_options).ConfigureAwait(false);
if (result.Errors?.Count > 0)
{
return BadRequest(result);
}
return Ok(result);
}
catch (Exception ex)
{
return BadRequest(ex);
}
}
}
}
public JObject Variables { get; set; }
在 BaseGraphQLQuery.cs
.BaseGraphQLQuery
类是 GraphQL 请求的实现,而不是 GraphQL 查询。重命名为 GraphQLRequest
或者将 Controller post action 中的参数名称更改为 BaseGraphQLQuery
.关于graphql - .Net 核心 3.1 + GraphQL ==> "error": "Unexpected end of JSON input",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60246358/