你是否已经厌倦了REST风格的API? 让咱们来聊一下GraphQL。 GraphQL提供了一种声明式的方式从服务器拉取数据。你能够从GraphQL官网中了解到GraphQL的全部优势。在这一系列博客中,我将展现如何在ASP.NET Core中集成GraphQL, 并使用GraphQL做为你的API查询语言。git
使用GraphQL的声明式查询,你能够自定义API返回的属性列表。这与REST API中每一个API只返回固定字段不一样。github
为了在C#中使用GraphQL, GraphQL社区中提供了一个开源组件graphql-dotnet
。本系列博客中咱们都将使用这个组件。web
首先咱们建立一个空的ASP.NET Core Appjson
dotnet new web --name chatper1
而后咱们添加对graphql-dotnet
库的引用c#
dotnet add package GraphQL
下面咱们来建立一个query
类, 咱们将它命名为HelloWorldQuery
。graphql-dotnet
中,查询类都须要继承ObjectGraphType
类,因此HelloWorldQuery
的代码以下浏览器
using GraphQL.Types; public class HelloWorldQuery : ObjectGraphType { public HelloWorldQuery() { Field<StringGraphType>( name: "hello", resolve: context => "world" ); } }
这里你可能注意到咱们使用了一个泛型方法Field
,并传递了一个GraphQL的字符串类型StringGraphType
来定义了一个hello
字段, resolve
参数是一个Func委托,在其中定义了如何返回当前字段的值,这里咱们是直接返回了一个字符串hello。服务器
查询类中的返回字段都是定义在查询类的构造函数中的app
如今咱们一个有了一个查询类,下一步咱们须要使用这个查询类构建一个结构(schema)。async
在Startup.cs
文件的Configure
方法中,使用如下代码替换原有代码函数
var schema = new Schema { Query = new HelloWorldQuery() }; app.Run(async (context) => { var result = await new DocumentExecuter() .ExecuteAsync(doc => { doc.Schema = schema; doc.Query = @" query { hello } "; }).ConfigureAwait(false); var json = new DocumentWriter(indent: true) .Write(result) await context.Response.WriteAsync(json); });
DocumentExecuter
类的ExecuteAsync
方法中咱们定义Action委托,并经过这个委托设置了一个ExecutionOptions
对象。这个对象初始化了咱们定义的结构(schema), 并执行了咱们定义的查询字符串。doc.Query
定义了一个查询字符串DocumentWriter
类实例的Write
被转换成一个JSON字符串下面咱们来运行一下这个程序
dotnet run
你将在浏览器中看到如下结果
{ "data": { "hello": "world" } }
从以上的例子中,你会发现使用GraphQL并不像想象中那么难。下面咱们能够在HelloWorldQuery
类的构造函数中再添加一个字段howdy
, 并指定这个字段会返回一个字符串universe
。
Field<StringGraphType>( name: "howdy", resolve: context => "universe" );
而后咱们继续修改Startup
类中的Configure
方法, 修改咱们以前定义的query
var schema = new Schema { Query = new HelloWorldQuery() }; app.Run(async (context) => { var result = await new DocumentExecuter() .ExecuteAsync(doc => { doc.Schema = schema; doc.Query = @" query { hello howdy } "; }).ConfigureAwait(false); var json = new DocumentWriter(indent: true) .Write(result); await context.Response.WriteAsync(json); });
从新启动项目后,结果以下
{ "data": { "hello": "world", "howdy": "universe" } }
本篇咱们只是接触了GraphQL的一些皮毛,你可能会对GraphQL声明式行为有不少问题,没有关系,后续博客中,咱们慢慢解开GraphQL的面纱。下一篇咱们将介绍如何建立一个中间件(Middleware)