这有两个部分。
- 界面
GraphQL.Http.IDocumentWriter
移至GraphQL.IDocumentWriter
.
- JSON 序列化被提取到两个不同的库中,GraphQL.NewtonsoftJson和GraphQL.SystemTextJson。
如果您使用的是服务器项目,则需要更新到 4.x。
如果您编写了自己的中间件,请参阅 2.x 到 3.0 升级指南。
Newtonsoft.Json 示例
using Newtonsoft.Json;
private static async Task ExecuteAsync(HttpContext context, ISchema schema)
{
GraphQLRequest request;
using (var reader = new StreamReader(context.Request.Body))
using (var jsonReader = new JsonTextReader(reader))
{
var ser = new JsonSerializer();
request = ser.Deserialize<GraphQLRequest>(jsonReader);
}
var executer = new DocumentExecuter();
var result = await executer.ExecuteAsync(options =>
{
options.Schema = schema;
options.Query = request.Query;
options.OperationName = request.OperationName;
options.Inputs = request.Variables.ToInputs();
});
context.Response.ContentType = "application/json";
context.Response.StatusCode = result.Errors?.Any() == true ? (int)HttpStatusCode.BadRequest : (int)HttpStatusCode.OK;
var writer = new GraphQL.NewtonsoftJson.DocumentWriter();
await writer.WriteAsync(context.Response.Body, result);
}
public class GraphQLRequest
{
public string OperationName { get; set; }
public string Query { get; set; }
public Newtonsoft.Json.Linq.JObject Variables { get; set; }
}
System.Text 示例
using System.Text.Json;
private static async Task ExecuteAsync(HttpContext context, ISchema schema)
{
var request = await JsonSerializer.DeserializeAsync<GraphQLRequest>
(
context.Request.Body,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true }
);
var executer = new DocumentExecuter();
var result = await executer.ExecuteAsync(options =>
{
options.Schema = schema;
options.Query = request.Query;
options.OperationName = request.OperationName;
options.Inputs = request.Variables.ToInputs();
});
context.Response.ContentType = "application/json";
context.Response.StatusCode = 200; // OK
var writer = new GraphQL.SystemTextJson.DocumentWriter();
await writer.WriteAsync(context.Response.Body, result);
}
public class GraphQLRequest
{
public string OperationName { get; set; }
public string Query { get; set; }
[JsonConverter(typeof(GraphQL.SystemTextJson.ObjectDictionaryConverter))]
public Dictionary<string, object> Variables { get; set; }
}