+-
从.Net C#控制台应用程序客户端获取并配置Graphql请求

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

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 });

我对这个话题完全陌生,并感谢任何帮助。非常感谢!!

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);