
前文:ASP.NET Core中使用GraphQL - 第一章 Hello World
中間件
如果你熟悉ASP.NET Core的中間件,你可能會注意到之前的博客中我們已經使用了一個中間件,
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);
});
這個中間件負責輸出了當前查詢的結果。
中間件的定義:
中間件是裝載在應用程序管道中的組件,負責處理請求和響應,每一個中間件
- 可以選擇是否傳遞請求到應用程序管道中的下一個組件
- 可以在應用程序管道中下一個組件運行前和運行后進行一些操作
實際上中間件是一個委托,或者更精確的說是一個請求委托(Request Delegate)。 正如他的名字一樣,中間件會處理請求,並決定是否將他委托到應用程序管道中的下一個中間件中。在我們前面的例子中,我們使用IApplicationBuilder類的Run()方法配置了一個請求委托。
使用動態查詢體替換硬編碼查詢體
在我們之前的例子中,中間件中的代碼非常簡單,它僅是返回了一個固定查詢的結果。然而在現實場景中,查詢應該是動態的,因此我們必須從請求中讀取查詢體。
在服務器端,每一個請求委托都可以接受一個HttpContext參數。如果一個查詢體是通過POST請求發送到服務器的,你可以很容易的使用如下代碼獲取到請求體中的內容。
string body;
using (var streamReader = new StreamReader(httpContext.Request.Body))
{
body = await streamReader.ReadToEndAsync();
}
在獲取請求體內容之前,為了不引起任何問題,我們需要先檢測一些當前請求
- 是否是一個
POST請求 - 是否使用了特定的Url, 例如
/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
