Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

A GraphQL Client for .NET Standard

License

NotificationsYou must be signed in to change notification settings

graphql-dotnet/graphql-client

Repository files navigation

A GraphQL Client for .NET Standard over HTTP.

Provides the following packages:

PackageDownloadsNuget Latest
GraphQL.ClientNugetNuget
GraphQL.Client.AbstractionsNugetNuget
GraphQL.Client.Abstractions.WebsocketNugetNuget
GraphQL.Client.LocalExecutionNugetNuget
GraphQL.Client.Serializer.NewtonsoftNugetNuget
GraphQL.Client.Serializer.SystemTextJsonNugetNuget
GraphQL.PrimitivesNugetNuget

Specification

The Library will try to follow the following standards and documents:

Usage

The intended use ofGraphQLHttpClient is to keep one instance alive per endpoint (obvious in case you'reoperating full websocket, but also true for regular requests) and is built with thread-safety in mind.

Create a GraphQLHttpClient

// To use NewtonsoftJsonSerializer, add a reference to// NuGet package GraphQL.Client.Serializer.NewtonsoftvargraphQLClient=newGraphQLHttpClient("https://api.example.com/graphql",newNewtonsoftJsonSerializer());

Note

GraphQLHttpClient is meant to be used as a single long-lived instance per endpoint (i.e. register as singleton in a DI system), which should be reused for multiple requests.

Create a GraphQLRequest:

Simple Request:

varheroRequest=newGraphQLRequest{Query="""    {        hero {            name        }    }    """};

OperationName and Variables Request:

varpersonAndFilmsRequest=newGraphQLRequest{Query="""    query PersonAndFilms($id: ID) {        person(id: $id) {            name            filmConnection {                films {                    title                }            }        }    }    """,OperationName="PersonAndFilms",Variables=new{id="cGVvcGxlOjE="}};

Warning

Be careful when usingbyte[] in your variables object, as most JSON serializers will treat that as binary data.

If you really need to send alist of bytes with abyte[] as a source, then convert it to aList<byte> first, which will tell the serializer to output a list of numbers instead of a base64-encoded string.

Execute Query/Mutation

publicclassResponseType{publicPersonTypePerson{get;set;}}publicclassPersonType{publicstringName{get;set;}publicFilmConnectionTypeFilmConnection{get;set;}}publicclassFilmConnectionType{publicList<FilmContentType>Films{get;set;}}publicclassFilmContentType{publicstringTitle{get;set;}}vargraphQLResponse=awaitgraphQLClient.SendQueryAsync<ResponseType>(personAndFilmsRequest);varpersonName=graphQLResponse.Data.Person.Name;

Using the extension method for anonymously typed responses (namespaceGraphQL.Client.Abstractions) you could achieve the same result with the following code:

vargraphQLResponse=awaitgraphQLClient.SendQueryAsync(personAndFilmsRequest,()=>new{person=newPersonType()});varpersonName=graphQLResponse.Data.person.Name;

Important

Note that the field in the GraphQL response which gets deserialized into the response object is thedata field.

A common mistake is to try to directly use thePersonType class as response type (because thats thething you actually want to query), but the returned response object contains a propertyperson containing aPersonType object (like theResponseType modelled above).

Use Subscriptions

publicclassUserJoinedSubscriptionResult{publicChatUserUserJoined{get;set;}publicclassChatUser{publicstringDisplayName{get;set;}publicstringId{get;set;}}}

Create subscription

varuserJoinedRequest=newGraphQLRequest{Query=@"    subscription {        userJoined{            displayName            id        }    }"};IObservable<GraphQLResponse<UserJoinedSubscriptionResult>>subscriptionStream=client.CreateSubscriptionStream<UserJoinedSubscriptionResult>(userJoinedRequest);varsubscription=subscriptionStream.Subscribe(response=>{Console.WriteLine($"user '{response.Data.UserJoined.DisplayName}' joined")});

End Subscription

subscription.Dispose();

Automatic persisted queries (APQ)

Automatic persisted queries (APQ) are supported since client version 6.1.0.

APQ can be enabled by configuringGraphQLHttpClientOptions.EnableAutomaticPersistedQueries to resolve totrue.

By default, the client will automatically disable APQ for the current session if the server responds with aPersistedQueryNotSupported error or a 400 or 600 HTTP status code.This can be customized by configuringGraphQLHttpClientOptions.DisableAPQ.

To re-enable APQ after it has been automatically disabled,GraphQLHttpClient needs to be disposed an recreated.

APQ works by first sending a hash of the query string to the server, and only sending the full query string if the server has not yet cached a query with a matching hash.With queries supplied as a string parameter toGraphQLRequest, the hash gets computed each time the request is sent.

When you want to reuse a query string (propably to leverage APQ 😉), declare the query using theGraphQLQuery class. This way, the hash gets computed once on constructionof theGraphQLQuery object and handed down to eachGraphQLRequest using the query.

GraphQLQueryquery=new("""                         query PersonAndFilms($id: ID) {                             person(id: $id) {                                 name                                 filmConnection {                                     films {                                         title                                     }                                 }                             }                         }                         """);vargraphQLResponse=awaitgraphQLClient.SendQueryAsync<ResponseType>(query,"PersonAndFilms",new{id="cGVvcGxlOjE="});

Syntax Highlighting for GraphQL strings in IDEs

.NET 7.0 introduced theStringSyntaxAttribute to have a unified way of telling what data is expected in a givenstring orReadOnlySpan<char>. IDEs like Visual Studio and Rider can then use this to provide syntax highlighting and checking.

From v6.0.4 on all GraphQL string parameters in this library are decorated with the[StringSyntax("GraphQL")] attribute.

Currently, there is no native support for GraphQL formatting and syntax highlighting in Visual Studio, but theGraphQLTools Extension provides that for you.

For Rider, JetBrains provides aPlugin, too.

To leverage syntax highlighting in variable declarations, use theGraphQLQuery class.

Useful Links

Blazor WebAssembly Limitations

Blazor WebAssembly differs from other platforms as it does not support all features of other .NET runtime implementations. For instance, the following WebSocket options properties are not supported and will not be set:

About

A GraphQL Client for .NET Standard

Topics

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors27

Languages


[8]ページ先頭

©2009-2026 Movatter.jp