【问题标题】:GraphQL Documentation Explorer not showing in browser .net core 3.1GraphQL 文档资源管理器未在浏览器 .net core 3.1 中显示
【发布时间】:2021-09-29 14:27:54
【问题描述】:

我是 GraphQL 的新手,我已经使用 GraphQL 构建了一个示例项目,该项目运行良好,但 'Documentation Explore'(我的自定义架构)未加载到 Browser .net core 3.1 中也附加了 StartUp.cs。 注意:在 .net core 2.0 中有效。

这里是 startup.cs

using GraphiQl;
using GraphQL;
using GraphQL.Server;
using GraphQL.Types;
{
    public class Startup
    {

        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<IISServerOptions>(options =>
            {
                options.AllowSynchronousIO = true;
            });

            services.AddSingleton<IDependencyResolver>(c => new FuncDependencyResolver(type => c.GetRequiredService(type)));

            services.AddDbContext<RealEstateContext>(options => options.UseSqlServer(Configuration["ConnectionStrings:RealEstateDb"]));
            services.AddScoped<IDocumentExecuter, DocumentExecuter>();
            services.AddScoped<PropertyQuery>();
            services.AddScoped<PropertyMutation>();
            services.AddScoped<PropertyType>();
            services.AddScoped<ConstituencyType>();
            services.AddScoped<PropertyInputType>();
            services.AddScoped<PaymentType>();
                    services.AddGraphQL(options =>
            {
                options.EnableMetrics = true;
                options.ExposeExceptions = true;
            }).AddWebSockets();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env,RealEstateContext db)
        {
            app.UseWebSockets();
            app.UseGraphQLWebSockets<RealEstateSchema>("/graphql");
            app.UseGraphQL<RealEstateSchema>("/graphql");
            db.EnsureSeedData();
        }

    }
}

Here is for your reference

【问题讨论】:

    标签: graphql .net-core-3.1


    【解决方案1】:

    您的查询结果是否以“数据”开头?如果不是,那么这可能是问题所在。 Documentation Explorer(它是一个 React 应用程序)期望其元数据查询的结果以“数据”开头。

    我在GraphQLController中添加了如下代码,然后文档就出现了。

    [Route("/graphql")]
    [HttpPost]
    public async Task<IActionResult> Post([FromBody] GraphQLQueryDTO query)
    {
        var result = await _executer.ExecuteAsync(_ =>
        {
            _.Schema = _schema;
            _.Query = query.Query;
            _.Inputs = query.Variables?.ToInputs();
    
        });
    
        if (result.Errors?.Count > 0) {
            return BadRequest(result.Errors[0].ToString());
        }
    
        // The response json is not starting with "data" - maybe to look prettier
        // This issue with this is that when GraphiQL requests the schema, GraphiQL
        // is expecting a response that starts "data". So I am adding "data" to the
        // front of the response if this is a schema request.  
        if (typeof(Dictionary<string, object>).IsInstanceOfType(result.Data)) {
            var dictData = (Dictionary<string, object>)result.Data;
            if (dictData.ContainsKey("__schema")) {
                var result2 = new Dictionary<string, object>();
                result2.Add("data", dictData);
                return Ok(result2);
            } else { 
                return Ok(result.Data);
            }
        }
        return Ok(result);
    }
    

    【讨论】:

      【解决方案2】:

      尽管遵循 Stack Overflow 和 Github 上的所有建议,但我遇到了同样的问题(架构和文档未在 Playground 上加载)。

      当我分配SchemaQuery属性后解决了;

      之前:

      public class ApiSchema : Schema, ISchema
      {
          public ApiSchema(IServiceProvider serviceProvider) : base(serviceProvider)
          {
              Mutation = serviceProvider.GetRequiredService<ApiMutation>();
          }
      }
      

      之后:

      public class ApiSchema : Schema, ISchema
      {
          public ApiSchema(IServiceProvider serviceProvider) : base(serviceProvider)
          {
              Query = serviceProvider.GetRequiredService<ApiQuery>();
              Mutation = serviceProvider.GetRequiredService<ApiMutation>();
          }
      }
      

      这是我的 Startup.cs 文件:

          public class Startup
          {
              public Startup(IConfiguration configuration)
              {
                  Configuration = configuration;
              }
      
              public IConfiguration Configuration { get; }
      
              public void ConfigureServices(IServiceCollection services)
              {
                  services.AddControllers(options => options.EnableEndpointRouting = false)
                      .AddNewtonsoftJson();
                  services.AddOptions();
      
                  services.AddScoped<TestInputType>();
                  services.AddScoped<TestType>();
                  services.AddScoped<ApiMutation>();
                  services.AddScoped<ApiSchema>();
                  services.AddGraphQL()
                      .AddErrorInfoProvider(options => options.ExposeExceptionStackTrace =true)
                      .AddNewtonsoftJson()
                      .AddDataLoader()
                      .AddGraphTypes(ServiceLifetime.Scoped);
                  services.Configure<IISServerOptions>(options =>
                  {
                      options.AllowSynchronousIO = true;
                  });
              }
              
              public void Configure(IApplicationBuilder app, IHostEnvironment env)
              {
                  if (env.IsDevelopment())
                  {
                      app.UseDeveloperExceptionPage();
                  }
                  else
                  {
                      app.UseExceptionHandler("/Home/Error");
                      app.UseHsts();
                  }
      
                  app.UseStaticFiles();
                  app.UseCookiePolicy();
                  app.UseRouting();
                  app.UseGraphQL<ApiSchema>();
                  app.UseWebSockets();
                  app.UseGraphQLPlayground(new PlaygroundOptions());
      
      
                  app.UseEndpoints(endpoints =>
                  {
                      endpoints.MapControllerRoute(
                          name: "default",
                          pattern: "{controller=Home}/{action=Index}/{id?}");
                      endpoints.MapGraphQLPlayground();
                  });
      
              }
          }
      

      这是我的 .csproj 文件:

      <Project Sdk="Microsoft.NET.Sdk.Web">
      
        <PropertyGroup>
          <TargetFramework>netcoreapp3.1</TargetFramework>
          <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
        </PropertyGroup>
      
        <ItemGroup>
          <PackageReference Include="GraphQL.Server.Transports.AspNetCore.NewtonsoftJson" Version="5.0.2" />
          <PackageReference Include="GraphQL.Server.Ui.Playground" Version="5.0.2" />
          
          <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.18" />
          <PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
        </ItemGroup>
      
        <ItemGroup>
          <ProjectReference Include="....csproj" />
        </ItemGroup>
      
      </Project>
      
      

      【讨论】:

        猜你喜欢
        • 2021-04-16
        • 2019-06-06
        • 2020-07-23
        • 1970-01-01
        • 1970-01-01
        • 2019-11-19
        • 2012-11-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多