4
Answers

how to use GraphQL in c#

using GraphQL; using GraphQL.Types; using GraphQL.SystemTextJson; How to use these references in VS 2019 C#

Answers (4)

4
Photo of Amit Mohanty
16 52.5k 6.1m 1y

Right-click on your project in Solution Explorer, select "Manage NuGet Packages...", and then search and install the following packages:

  • GraphQL
  • GraphQL.Server.Transports.AspNetCore
  • GraphQL.SystemTextJson
2
Photo of Jaimin Shethiya
49 30.7k 606k 1y

Hello,

Plese refer the below links, 

https://dev.to/dotnet/learn-how-you-can-use-graphql-in-net-core-and-c-4h96
https://codewithmukesh.com/blog/graphql-in-aspnet-core/
https://www.c-sharpcorner.com/article/building-api-in-net-core-with-graphql2/
https://code-maze.com/graphql-aspnetcore-basics/

 

Thanks

2
Photo of Mayooran Navamany
276 6.9k 185.3k 1y
  1. Install GraphQL NuGet Packages: Right-click on your project in the Solution Explorer and select "Manage NuGet Packages". Search for and install the following packages:

    • GraphQL (The main GraphQL package)
    • GraphQL.Types (Provides types for defining GraphQL schema)
    • GraphQL.SystemTextJson (Provides JSON serialization support for GraphQL)
  2. Define Your GraphQL Schema: Create GraphQL types that represent your data schema. You can do this by defining classes that inherit from ObjectGraphType from the GraphQL.Types namespace.

  3. Define Your Query or Mutation: Implement your GraphQL query and mutation by defining classes that inherit from ObjectGraphType and configuring their fields.

  4. Configure the Schema and Resolver: Configure your schema using the Schema class provided by the GraphQL namespace. Define resolvers for each field to specify how to fetch data for that field.

  5. Expose GraphQL Endpoint (if using ASP.NET Core): If you're building a web application using ASP.NET Core, you need to expose a GraphQL endpoint. You can do this by adding a controller and defining a route for your GraphQL endpoint.

Here's a simple example demonstrating how you can set up a GraphQL server in C# using the mentioned libraries:

using System;
using GraphQL;
using GraphQL.Types;
using GraphQL.SystemTextJson;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;

namespace GraphQLDemo
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            // Add GraphQL services
            services.AddSingleton<IDependencyResolver>(s => new FuncDependencyResolver(s.GetRequiredService));
            services.AddSingleton<IDocumentExecuter, DocumentExecuter>();
            services.AddSingleton<IDocumentWriter, DocumentWriter>();

            // Add your GraphQL types
            services.AddSingleton<ISchema, MySchema>();
        }
    }

    // Define your GraphQL types
    public class MySchema : Schema
    {
        public MySchema(IServiceProvider provider) : base(provider)
        {
            Query = provider.GetRequiredService<MyQuery>();
            Mutation = provider.GetRequiredService<MyMutation>();
        }
    }

    public class MyQuery : ObjectGraphType
    {
        public MyQuery()
        {
            Field<StringGraphType>(
                name: "hello",
                resolve: context => "world"
            );
        }
    }

    public class MyMutation : ObjectGraphType
    {
        public MyMutation()
        {
            Field<StringGraphType>(
                name: "echo",
                arguments: new QueryArguments(new QueryArgument<StringGraphType> { Name = "message" }),
                resolve: context => context.GetArgument<string>("message")
            );
        }
    }

    // Expose GraphQL endpoint using ASP.NET Core
    [Route("graphql")]
    public class GraphQLController : ControllerBase
    {
        private readonly IDocumentExecuter _documentExecuter;
        private readonly IDocumentWriter _documentWriter;
        private readonly ISchema _schema;

        public GraphQLController(IDocumentExecuter documentExecuter, IDocumentWriter documentWriter, ISchema schema)
        {
            _documentExecuter = documentExecuter;
            _documentWriter = documentWriter;
            _schema = schema;
        }

        [HttpPost]
        public async Task<IActionResult> Post([FromBody] GraphQLRequest request)
        {
            var executionOptions = new ExecutionOptions
            {
                Schema = _schema,
                Query = request.Query,
                Inputs = request.Variables.ToInputs(),
            };

            var result = await _documentExecuter.ExecuteAsync(executionOptions).ConfigureAwait(false);

            if (result.Errors?.Count > 0)
            {
                return BadRequest(result.Errors);
            }

            return Ok(result);
        }
    }

    // Model for GraphQL request
    public class GraphQLRequest
    {
        public string Query { get; set; }
        public JObject Variables { get; set; }
    }
}
1
Photo of Jaydeep Patil
104 18.1k 2.6m 1y

Hi,

Check my below article for the same where you will get step by step information.


https://www.c-sharpcorner.com/article/graphql-introduction-and-product-application-using-net-core-7/