使用和配置来自.Net C#控制台应用程序客户端的Graphql请求

时间:2018-09-02 06:30:05

标签: c# .net graphql

我正在尝试从C#客户端使用Graphql Api。为此,我使用了GraphQl.Net Nuget包。问题是,我不知道如何设置Api Url,因为我没有HttpRequest对象,这还会导致其他问题,例如我无法设置身份验证标头和发送带有请求的令牌。我的代码如下:

public void Post(TestGraphQl.GraphQLQuery query)
{
   var inputs = query.Variables.ToInputs();
   var queryToExecute = query.Query;

   var result = _executer.ExecuteAsync(_ =>
   {
     _.Schema = _schema;
     _.Query = queryToExecute;
     _.OperationName = query.OperationName;
     _.Inputs = inputs;

     //_.ComplexityConfiguration = new ComplexityConfiguration { MaxDepth = 15 };
     _.FieldMiddleware.Use<InstrumentFieldsMiddleware>();

    }).Result;

    var httpResult = result.Errors?.Count > 0
                ? HttpStatusCode.BadRequest
                : HttpStatusCode.OK;

    var json = _writer.Write(result);
}

呼叫者看起来像这样:

var jObject = new Newtonsoft.Json.Linq.JObject();
jObject.Add("id", deviceId);
client.Post(new GraphQLQuery { Query = "query($id: String) { device (id: $id) { displayName, id } }", Variables = jObject });

我是这个主题的新手,感谢您的帮助。非常感谢!

2 个答案:

答案 0 :(得分:2)

这对我有效。您将需要GraphQL.Client软件包。

var client = new GraphQLHttpClient({Api Url}, new NewtonsoftJsonSerializer());

var request = new GraphQLRequest
{
    Query = {query}
};

var response = await client.SendQueryAsync<{Class for deserialization}>(request);

答案 1 :(得分:0)

不确定您是否还在寻找它。可以始终使用GraphQl.Client nuget来实现这一目标。要使用的示例代码为

var  query = @"query($id: String) { device (id: $id) { displayName, id } }";
var request = new GraphQLRequest(){
                                Query = query,
                                Variables = new {id =123}  
                            };

var graphQLClient = new GraphQLClient("http://localhost:8080/api/GraphQL");

graphQLClient.DefaultRequestHeaders.Add("Authorization", "yourtoken");

var graphQLResponse = await graphQLClient.PostAsync(request);
            
Console.WriteLine(graphQLResponse.Data);