前文:ASP.NET Core中使用GraphQL - 第一章 Hello Worldhtml
若是你熟悉ASP.NET Core的中间件,你可能会注意到以前的博客中咱们已经使用了一个中间件,git
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); });
这个中间件负责输出了当前查询的结果。github
中间件的定义:json
中间件是装载在应用程序管道中的组件,负责处理请求和响应,每个中间件c#
- 能够选择是否传递请求到应用程序管道中的下一个组件
- 能够在应用程序管道中下一个组件运行前和运行后进行一些操做
来源: Microsoft Documentationapi
实际上中间件是一个委托,或者更精确的说是一个请求委托(Request Delegate)。 正如他的名字同样,中间件会处理请求,并决定是否将他委托到应用程序管道中的下一个中间件中。在咱们前面的例子中,咱们使用IApplicationBuilder
类的Run()
方法配置了一个请求委托。服务器
在咱们以前的例子中,中间件中的代码很是简单,它仅是返回了一个固定查询的结果。然而在现实场景中,查询应该是动态的,所以咱们必须从请求中读取查询体。app
在服务器端,每个请求委托均可以接受一个HttpContext
参数。若是一个查询体是经过POST请求发送到服务器的,你能够很容易的使用以下代码获取到请求体中的内容。async
string body; using (var streamReader = new StreamReader(httpContext.Request.Body)) { body = await streamReader.ReadToEndAsync(); }
在获取请求体内容以前,为了避免引发任何问题,咱们须要先检测一些当前请求ui
POST
请求 /api/graphql
所以咱们须要对代码进行调整。
if(context.Request.Path.StartsWithSegments("/api/graphql") && string.Equals(context.Request.Method, "POST", StringComparison.OrdinalIgnoreCase)) { string body; using (var streamReader = new StreamReader(context.Request.Body)) { body = await streamReader.ReadToEndAsync(); } .... .... ....
一个请求体能够包含不少字段,这里咱们约定传入graphql
查询体字段名称是query
。所以咱们能够将请求体中的JSON字符串转换成一个包含Query
属性的复杂类型。
这个复杂类型代码以下:
public class GraphQLRequest { public string Query { get; set; } }
下一步咱们要作的就是,反序列化当前请求体的内容为一个GraphQLRequest
类型的实例。这里咱们须要使用Json.Net
中的静态方法JsonConvert.DeserializeObjct
来替换以前的硬编码的查询体。
var request = JsonConvert.DeserializeObject<GraphQLRequest>(body); var result = await new DocumentExecuter().ExecuteAsync(doc => { doc.Schema = schema; doc.Query = request.Query; }).ConfigureAwait(false);
在完成以上修改以后,Startup.cs
文件的Run
方法应该是这个样子的。
app.Run(async (context) => { if (context.Request.Path.StartsWithSegments("/api/graphql") && string.Equals(context.Request.Method, "POST", StringComparison.OrdinalIgnoreCase)) { string body; using (var streamReader = new StreamReader(context.Request.Body)) { body = await streamReader.ReadToEndAsync(); var request = JsonConvert.DeserializeObject<GraphQLRequest>(body); var schema = new Schema { Query = new HelloWorldQuery() }; var result = await new DocumentExecuter() .ExecuteAsync(doc => { doc.Schema = schema; doc.Query = request.Query; }).ConfigureAwait(false); var json = new DocumentWriter(indent: true) .Write(result); await context.Response.WriteAsync(json); } } });
如今咱们可使用POSTMAN来建立一个POST请求, 请求结果以下:
结果正确返回了。
本篇源代码: https://github.com/lamondlu/GraphQL_Blogs/tree/master/Part%20II