I'm trying to develop a simple graphql api in .net core. When I run the application, I don't see any schema in the document explorer.
Everything seems to be right. I could not find the problem.
.net core version 3.1
graphql version 3.2
GraphiQl version 2.0
code part as below
Model
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
}
Type
public class CustomerType : ObjectGraphType<Customer>
{
public CustomerType()
{
Field(x => x.Id);
Field(x => x.Name);
}
}
Query
public class GraphQuery : ObjectGraphType
{
public GraphQuery()
{
Field<ListGraphType<CustomerType>>(
"customers",
resolve: context =>
{
return new List<Customer>
{
new Customer
{
Id=1,
Name="Faruk"
}
};
});
}
}
Schema
public class GraphSchema : Schema
{
public GraphSchema(IServiceProvider provider)
: base(provider)
{
Query = provider.GetRequiredService<GraphQuery>();
}
}
Controller
namespace GqlDemo2.Api.Controllers
{
[ApiController]
[Route("graphql")]
public class GraphqlController : ControllerBase
{
private readonly IDocumentExecuter _documentExecuter;
private readonly ISchema _schema;
public GraphqlController(ISchema schema, IDocumentExecuter documentExecuter)
{
_schema = schema;
_documentExecuter = documentExecuter;
}
[HttpPost]
public async Task<ActionResult> PostAsync([FromBody] GraphQLQuery query)
{
if (query == null) { throw new ArgumentNullException(nameof(query)); }
var inputs = query.Variables.ToInputs();
var executionOptions = new ExecutionOptions
{
Schema = _schema,
Query = query.Query,
Inputs = inputs
};
var result = await _documentExecuter.ExecuteAsync(executionOptions).ConfigureAwait(false);
if (result.Errors?.Count > 0)
{
return BadRequest(result);
}
return Ok(result);
}
}
}
Startup
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddHttpContextAccessor();
services.AddSingleton<IDocumentExecuter, DocumentExecuter>();
services.AddSingleton<CustomerType>();
services.AddSingleton<GraphQuery>();
var sp = services.BuildServiceProvider();
services.AddSingleton<ISchema>(new GraphSchema(new FuncServiceProvider(type => sp.GetService(type))));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseGraphiQl("/graphiql");
app.UseHttpsRedirection();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
clear your browser cache and cookies because that solve mine