GraphQL 既是一种用于 API 的查询语言也是一个知足你数据查询的运行时。GraphQL 对你的 API 中的数据提供了一套易于理解的完整描述,使得客户端可以准确地得到它须要的数据,并且没有任何冗余,也让 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