C# / .NET:GraphQL.Client(GraphQL 客户端)
C# / .NET:GraphQL.Client(GraphQL 客户端)
GraphQL.Client 是 .NET 生态中一款轻量级、功能完善的 GraphQL 客户端库,由 graphql-dotnet 组织维护,支持 HTTP 与 WebSocket 传输协议。它提供了简洁的 API,帮助开发者在 .NET 应用中快速构建 GraphQL 请求、处理响应,并支持订阅(Subscription)等高级特性。
基本信息
- 项目名称:GraphQL.Client
- 项目描述:A GraphQL Client for .NET
- GitHub 仓库:graphql-dotnet/graphql-client
- 所属分类:生态项目与库
主要特性
- 支持 .NET Standard 2.0+、.NET Core 3.0+ 及 .NET 5/6/7/8 等现代 .NET 框架。
- 提供强类型与原始字符串两种查询方式。
- 支持 GraphQL 变量、操作名称、片段等完整查询语法。
- 内置对 GraphQL over HTTP 和 GraphQL over WebSocket 的支持。
- 支持订阅(Subscription),适用于实时数据场景。
- 支持文件上传(multipart/form-data)。
- 支持请求取消(CancellationToken)。
- 提供与
Microsoft.Extensions.DependencyInjection的集成扩展。 - 支持自定义
HttpClient、序列化器与 WebSocket 连接选项。
安装
通过 NuGet 安装 GraphQL.Client 主包:
bash
dotnet add package GraphQL.Client
若需要使用 WebSocket 订阅功能,还需安装序列化与 WebSocket 支持包:
bash
dotnet add package GraphQL.Client.Serializer.SystemTextJson
dotnet add package GraphQL.Client.Abstractions.Websocket
也可以使用基于 Newtonsoft.Json 的序列化包:
bash
dotnet add package GraphQL.Client.Serializer.Newtonsoft
快速开始
以下示例使用 SystemTextJson 序列化器,向公共 GraphQL API(如 https://countries.trevorblades.com/)发送查询请求。
1. 创建客户端
csharp
using GraphQL.Client.Http;
using GraphQL.Client.Serializer.SystemTextJson;
var graphQLClient = new GraphQLHttpClient("https://countries.trevorblades.com/", new SystemTextJsonSerializer());
// 如需配置 WebSocket 连接(用于订阅),可调用:
// graphQLClient.WebsocketEndpoint = new Uri("wss://countries.trevorblades.com/graphql");
2. 定义查询请求
使用 GraphQLRequest 定义查询字符串与变量:
csharp
using GraphQL;
var request = new GraphQLRequest
{
Query = """
query CountryQuery($code: ID!) {
country(code: $code) {
name
capital
currency
}
}
""",
Variables = new { code = "CN" }
};
3. 发送请求并处理响应
csharp
var response = await graphQLClient.SendQueryAsync<CountryResponse>(request);
Console.WriteLine($"国家: {response.Data.Country.Name}");
Console.WriteLine($"首都: {response.Data.Country.Capital}");
定义响应类型:
csharp
public class CountryResponse
{
public Country Country { get; set; }
}
public class Country
{
public string Name { get; set; }
public string Capital { get; set; }
public string Currency { get; set; }
}
注意:若查询的返回类型为集合或标量,请使用
SendQueryAsync<T>的对应泛型类型,或直接使用GraphQLResponse<T>。
使用变量
推荐将变量与查询分离,便于复用和避免拼接字符串:
csharp
var request = new GraphQLRequest
{
Query = """
query($id: ID!) {
user(id: $id) {
id
name
email
}
}
""",
Variables = new { id = "123" }
};
发送变更(Mutation)
变更与查询的用法完全一致:
csharp
var request = new GraphQLRequest
{
Query = """
mutation($input: CreateUserInput!) {
createUser(input: $input) {
id
name
}
}
""",
Variables = new
{
input = new
{
name = "Alice",
email = "alice@example.com"
}
}
};
var response = await graphQLClient.SendMutationAsync<CreateUserResponse>(request);
订阅(Subscription)
订阅需要建立 WebSocket 连接。先安装 GraphQL.Client.Abstractions.Websocket 包,然后创建订阅:
csharp
using GraphQL.Client.Abstractions.Websocket;
var subscriptionRequest = new GraphQLRequest
{
Query = """
subscription {
userCreated {
id
name
}
}
"""
};
var subscription = graphQLClient.CreateSubscriptionStream<UserCreatedResponse>(subscriptionRequest);
await foreach (var response in subscription)
{
Console.WriteLine($"新用户: {response.Data.UserCreated.Name}");
}
配置选项
GraphQLHttpClient 构造函数接受可选的 GraphQLHttpClientOptions 配置:
csharp
var options = new GraphQLHttpClientOptions
{
EndPoint = new Uri("https://api.example.com/graphql"),
HttpMessageHandler = new HttpClientHandler
{
UseCookies = false
},
UseWebSocketForQueriesAndMutations = false,
WebSocketEndPoint = new Uri("wss://api.example.com/graphql")
};
var client = new GraphQLHttpClient(options, new SystemTextJsonSerializer());
常用配置项:
| 配置项 | 说明 |
|---|---|
EndPoint |
GraphQL HTTP 端点地址 |
WebSocketEndPoint |
GraphQL WebSocket 端点地址 |
HttpMessageHandler |
自定义 HttpMessageHandler(如代理、证书验证) |
UseWebSocketForQueriesAndMutations |
是否通过 WebSocket 发送查询与变更 |
ConfigureWebSocket |
配置 WebSocket 连接的委托 |
错误处理
GraphQL 响应中可能包含部分成功与错误信息,建议检查 Errors 属性:
csharp
var response = await client.SendQueryAsync<MyResponse>(request);
if (response.Errors != null && response.Errors.Length > 0)
{
foreach (var error in response.Errors)
{
Console.WriteLine($"GraphQL 错误: {error.Message}");
}
return;
}
// 正常处理 response.Data
文件上传
GraphQL.Client 支持多部分表单上传(需遵循 GraphQL 文件上传规范):
csharp
var request = new GraphQLRequest
{
Query = """
mutation($file: Upload!) {
uploadFile(file: $file) {
id
url
}
}
""",
Variables = new { file = new GraphQLFile("file", File.OpenRead("test.txt"), "test.txt") }
};
var response = await client.SendMutationAsync<UploadResponse>(request);
在 ASP.NET Core 中集成依赖注入
csharp
// Program.cs
builder.Services.AddGraphQLClient()
.ConfigureHttpClient(client =>
{
client.BaseAddress = new Uri("https://api.example.com/graphql");
})
.ConfigureWebSocketClient(client =>
{
client.Uri = new Uri("wss://api.example.com/graphql");
});
然后在服务中注入 GraphQLHttpClient 或 IGraphQLClient:
csharp
public class MyService
{
private readonly IGraphQLClient _client;
public MyService(IGraphQLClient client)
{
_client = client;
}
public async Task<User> GetUserAsync(string id)
{
var request = new GraphQLRequest
{
Query = "query($id: ID!) { user(id: $id) { id name } }",
Variables = new { id }
};
var response = await _client.SendQueryAsync<UserResponse>(request);
return response.Data.User;
}
}
相关资源
总结
GraphQL.Client 是 .NET 平台上成熟、易用的 GraphQL 客户端实现,提供了从简单查询到实时订阅、文件上传等完整功能。与 .NET 生态(如依赖注入、HttpClient 工厂)的无缝集成,使其成为 C# / .NET 项目中接入 GraphQL 服务的首选库之一。
帮助我们改进文档
发现翻译问题或内容错误?请告诉我们。
