GraphQL:从头开始
GraphQL 既是一种用于 API 的查询语言也是一个满足你数据查询的运行时。GraphQL 对你的 API 中的数据提供了一套易于理解的完整描述,使得客户端能够准确地获得它需要的数据,而且没有任何冗余,也让 API 更容易地随着时间推移而演进,还能用于构建强大的开发者工具。
——出自 https://graphql.cn
前面几篇博文介绍了GraphQL在asp.net core框架下的实例,初步了解到Hot Chocolate的功能,不如从这篇开始,细致的过一下Hot Chocoklate,看看.net下这个GrpahQL框架究竟做了点什么,我们又能做点什么。
首先使用HotChocolate有两种姿势,代码姿势(code-first)和脚手架姿势(schema-first),那长什么样呢?实例送上:
using HotChocolate;
using HotChocolate.Execution;
using HotChocolate.Types;
using System;
namespace GraphQLBase001
{
class Program
{
static void Main(string[] args)
{
var schemaString = @"
type Query {
hello: String
}";
Console.WriteLine("Schema-First");
SchemaFirst.Run(schemaString);
Console.WriteLine("Schema-First");
CodeFirst.Run(schemaString);
Console.WriteLine("PurCode-First");
PureCodeFirst.Run();
C.Run(schemaString);
D.Run(schemaString);
E.Run();
}
}
#region Schema-First
public class SchemaFirst
{
public static void Run(string schemaString)
{
var schema = SchemaBuilder
.New()
.AddDocumentFromString(schemaString)
.AddResolver("Query", "hello", () => "world")
.Create();
var executor = schema.MakeExecutable();
Console.WriteLine(executor.Execute("{ hello }").ToJson());
}
}
#endregion
#region Code-First
public class CodeFirst
{
public static void Run(string schemaString)
{
var schema = SchemaBuilder
.New()
.AddDocumentFromString(schemaString)
.BindComplexType<Query>()
.Create();
var executor = schema.MakeExecutable();
Console.WriteLine(executor.Execute("{ hello }").ToJson());
}
public class Query
{
/// <summary>
/// 目测这里只对Hello或GetHello免疫
/// </summary>
/// <returns></returns>
public string Hello() => "world";
}
}
#endregion
#region PureCode-First
public class PureCodeFirst
{
public static void Run()
{
var schema = SchemaBuilder
.New()
.AddQueryType<Query>()
.Create();
var executor = schema.MakeExecutable();
Console.WriteLine(executor.Execute("{ hello }").ToJson());
}
public class Query
{
/// <summary>
/// 目测这里只对Hello或GetHello免疫
/// </summary>
/// <returns></returns>
public string Hello() => "world";
}
}
#endregion
}
通过上面实例,这两种不同点在于Query是定义了一个类来实现,还是通过一个约定字符串来实现,本质上都是一个方法(也可以是属性要一个字符串的返回值)。如果你注意到了PureCode-First,这只是一个变种,不过这个看起来对一个C#程序来说情怀实足。
其中不管那种方式,执行api的方式始终不变"{hello}",这里我们实际上调用的是hello方法,不过看来也只有这样一个数据了。
想要更快更方便的了解相关知识,可以关注微信公众号

****欢迎关注我的asp.net core系统课程****
《asp.net core精要讲解》 https://ke.qq.com/course/265696
《asp.net core 3.0》 https://ke.qq.com/course/437517
《asp.net core项目实战》 https://ke.qq.com/course/291868
《基于.net core微服务》 https://ke.qq.com/course/299524
《asp.net core精要讲解》 https://ke.qq.com/course/265696
《asp.net core 3.0》 https://ke.qq.com/course/437517
《asp.net core项目实战》 https://ke.qq.com/course/291868
《基于.net core微服务》 https://ke.qq.com/course/299524
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构