知海

C# / .NET:graphql-dotnet(GraphQL for .NET)

graphql-github-io-zh-Hans生态项目与库

C# / .NET:graphql-dotnet(GraphQL for .NET)

graphql-dotnet 是为 .NET 平台实现的 GraphQL 库,支持 C# / F# / VB.NET。它遵循 GraphQL 规范,提供从 Schema 构建、查询解析到执行结果序列化的完整能力,可轻松集成 ASP.NET Core 等框架。

基本信息

快速开始

以下示例展示了如何使用 Schema.For 以 GraphQL Schema Definition Language(SDL)方式定义类型,并通过 ExecuteAsync 执行查询。

安装依赖

通过 NuGet 安装基础包及 JSON 序列化包:

bash 复制代码
dotnet add package GraphQL
dotnet add package GraphQL.SystemTextJson

示例代码

csharp 复制代码
using System;
using System.Threading.Tasks;
using GraphQL;
using GraphQL.Types;
using GraphQL.SystemTextJson; // First add PackageReference to GraphQL.SystemTextJson

public class Program
{
  public static async Task Main(string[] args)
  {
    var schema = Schema.For(@"
      type Query {
        hello: String
      }
    ");

    var json = await schema.ExecuteAsync(_ =>
    {
      _.Query = "{ hello }";
      _.Root = new { Hello = "Hello World!" };
    });

    Console.WriteLine(json);
  }
}

输出结果

json 复制代码
{
  "data": {
    "hello": "Hello World!"
  }
}

主要特性

  • 支持 GraphQL 规范(查询、变更、订阅、片段、指令等)。
  • 提供两种构建 Schema 的方式:SDL 字符串解析和代码优先(Type-first / Code-first)。
  • 内置数据加载器、验证、持久化查询等高级功能。
  • ASP.NET Core 中间件、依赖注入无缝集成。

更多资源

帮助我们改进文档

发现翻译问题或内容错误?请告诉我们。