### Sample Response (JSON) Source: https://github.com/graphql-dotnet/server/blob/master/README.md Example JSON response for a successful GraphQL query. ```json {"data":{"hero":"Luke Skywalker"}} ``` -------------------------------- ### Sample Request URL Source: https://github.com/graphql-dotnet/server/blob/master/README.md Example URL to send a GraphQL query to the configured endpoint. ```http http://localhost:5000/graphql?query={hero} ``` -------------------------------- ### Register GraphQL Services with AddGraphQL Source: https://context7.com/graphql-dotnet/server/llms.txt Use `AddGraphQL` to register core GraphQL services like the execution engine and schema with the ASP.NET Core DI container. This is the initial setup step for any GraphQL configuration. ```csharp using GraphQL; using Chat = MyApp.Schemas.Chat; var builder = WebApplication.CreateBuilder(args); builder.Services.AddSingleton(); builder.Services.AddGraphQL(b => b .AddAutoSchema(s => s .WithMutation() .WithSubscription())) .AddSystemTextJson() .AddDataLoader() .AddAuthorizationRule() .AddUserContextBuilder(ctx => new Dictionary { ["user"] = ctx.User })); var app = builder.Build(); app.UseDeveloperExceptionPage(); app.UseWebSockets(); app.UseGraphQL("/graphql"); await app.RunAsync(); ``` -------------------------------- ### Altair Middleware Setup Source: https://github.com/graphql-dotnet/server/blob/master/tests/ApiApprovalTests/netstandard20/GraphQL.Server.Ui.Altair.approved.txt Use the `UseGraphQLAltair` extension method to add the Altair UI middleware to your ASP.NET Core application pipeline. This method can be configured with a specific path and options. ```csharp public static Microsoft.AspNetCore.Builder.IApplicationBuilder UseGraphQLAltair(this Microsoft.AspNetCore.Builder.IApplicationBuilder app, string path = "/ui/altair", GraphQL.Server.Ui.Altair.AltairOptions? options = null) { } ``` -------------------------------- ### GraphQL Query with Interface Validation Example Source: https://github.com/graphql-dotnet/server/blob/master/README.md Demonstrates how authorization validation might be executed against graph fields or interface fields depending on the query structure, especially when using interfaces. ```graphql { cat { # validates against Cat.Name name # validates against Animal.Name ... on Animal { name } } } ``` -------------------------------- ### GraphQL User Context Configuration Source: https://github.com/graphql-dotnet/server/blob/master/README.md Configure a custom user context for GraphQL requests by implementing `IUserContextBuilder` or using a delegate with `AddUserContextBuilder` during service setup. ```csharp builder.Services.AddGraphQL(b => b .AddAutoSchema() .AddSystemTextJson() .AddUserContextBuilder(httpContext => new MyUserContext(httpContext))); ``` ```csharp public class MyUserContext : Dictionary { public ClaimsPrincipal User { get; } public MyUserContext(HttpContext context) { User = context.User; } } ``` -------------------------------- ### HTTP Transport - Direct Requests with cURL Source: https://context7.com/graphql-dotnet/server/llms.txt Examples of making GraphQL requests over HTTP using cURL. Supports GET for queries, POST with JSON, application/graphql, and multipart/form-data. CSRF header may be required for GET requests. ```bash # GET — simple query (CSRF header required by default in v8) curl "http://localhost:5000/graphql?query={hero{name}}" \ -H "GraphQL-Require-Preflight: 1" ``` ```bash # POST — JSON body (no CSRF header needed; Content-Type is not a "simple" type) curl -X POST http://localhost:5000/graphql \ -H "Content-Type: application/json" \ -d '{"query":"{ hero { name } }"}' ``` ```bash # POST — JSON body with variables and operation name curl -X POST http://localhost:5000/graphql \ -H "Content-Type: application/json" \ -d '{ "operationName": "GetHero", "query": "query GetHero($episode: Episode) { hero(episode: $episode) { name } }", "variables": { "episode": "JEDI" } }' ``` ```bash # POST — Batched requests (array) curl -X POST http://localhost:5000/graphql \ -H "Content-Type: application/json" \ -d '[{"query":"{hero{name}}"},{ ``` ```bash # POST — application/graphql raw query string curl -X POST http://localhost:5000/graphql \ -H "Content-Type: application/graphql" \ -d '{ hero { name } }' ``` ```json # Expected response (single): # {"data":{"hero":{"name":"Luke Skywalker"}}} ``` ```json # Expected response (batched): # [{"data":{"hero":{"name":"Luke Skywalker"}}},{ ``` ```bash query":"{count}"}]' ``` -------------------------------- ### Configure GraphQL HTTP Middleware with UseGraphQL Source: https://context7.com/graphql-dotnet/server/llms.txt Configure the `GraphQLHttpMiddleware` using `UseGraphQL` to handle various request types including GET, POST, and WebSockets. Options control features like batched requests, CSRF protection, file size limits, and response content types. ```csharp var app = builder.Build(); app.UseDeveloperExceptionPage(); app.UseIgnoreDisconnections(); // suppress OperationCanceledException on client disconnect app.UseWebSockets(); app.UseAuthentication(); app.UseAuthorization(); app.UseGraphQL("/graphql", opts => { opts.HandleGet = true; opts.HandlePost = true; opts.HandleWebSockets = true; opts.EnableBatchedRequests = true; opts.ExecuteBatchedRequestsInParallel = true; opts.ReadFormOnPost = false; // disable multipart/form-data by default opts.CsrfProtectionEnabled = true; // requires GraphQL-Require-Preflight header opts.CsrfProtectionHeaders = ["GraphQL-Require-Preflight"]; opts.ValidationErrorsReturnBadRequest = null; // auto: 400 for graphql-response+json, 200 for application/json opts.AuthorizationRequired = false; opts.AuthorizedRoles.Add("Administrator"); opts.AuthorizedPolicy = "MyPolicy"; opts.MaximumFileSize = 10 * 1024 * 1024; // 10 MB per file opts.MaximumFileCount = 5; opts.DefaultResponseContentType = Microsoft.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/graphql-response+json; charset=utf-8"); }); await app.RunAsync(); // Sample GET request: // curl http://localhost:5000/graphql?query={hero} -H "GraphQL-Require-Preflight: 1" // Expected response: // {"data":{"hero":"Luke Skywalker"}} // Sample POST request: // curl -X POST http://localhost:5000/graphql \ // -H "Content-Type: application/json" \ // -d '{"query":"{hero}"}' // Expected response: // {"data":{"hero":"Luke Skywalker"}} ``` -------------------------------- ### Program.cs Configuration Source: https://github.com/graphql-dotnet/server/blob/master/README.md Configure GraphQL services, register the schema and serializer, and set up the HTTP pipeline with GraphQL middleware and UI. ```csharp using GraphQL; var builder = WebApplication.CreateBuilder(args); builder.Services.AddGraphQL(b => b .AddAutoSchema() // schema .AddSystemTextJson()); // serializer var app = builder.Build(); app.UseDeveloperExceptionPage(); app.UseWebSockets(); app.UseGraphQL("/graphql"); // url to host GraphQL endpoint app.UseGraphQLGraphiQL( "/", // url to host GraphiQL at new GraphQL.Server.Ui.GraphiQL.GraphiQLOptions { GraphQLEndPoint = "/graphql", // url of GraphQL endpoint SubscriptionsEndPoint = "/graphql", // url of GraphQL endpoint }); await app.RunAsync(); ``` -------------------------------- ### HttpGetValidationRule Source: https://github.com/graphql-dotnet/server/blob/master/tests/ApiApprovalTests/netcoreapp31/GraphQL.Server.Transports.AspNetCore.approved.txt A validation rule for GET requests in GraphQL. ```APIDOC ## HttpGetValidationRule ### Description A validation rule specifically for handling GET requests in GraphQL. ### Constructor - **HttpGetValidationRule()**: Initializes a new instance of the `HttpGetValidationRule` class. ### Methods - **GetPreNodeVisitorAsync(ValidationContext context)**: Gets the pre-node visitor for validation. ``` -------------------------------- ### Project File Configuration (XML) Source: https://github.com/graphql-dotnet/server/blob/master/README.md Add the GraphQL.Server.All nuget package to your project file to include all necessary GraphQL server components. ```xml net6.0 enable enable ``` -------------------------------- ### Configure GraphQL Endpoint with Route Handlers Source: https://github.com/graphql-dotnet/server/blob/master/README.md Set up GraphQL endpoints using MapGet and MapPost for minimal APIs, returning GraphQLExecutionHttpResult. MapGet is required for WebSocket support. ```csharp var app = builder.Build(); app.UseDeveloperExceptionPage(); app.UseWebSockets(); // configure the graphql endpoint at "/graphql", using GraphQLExecutionHttpResult // map GET in order to support both GET and WebSocket requests app.MapGet("/graphql", () => new GraphQLExecutionHttpResult()); // map POST to handle standard GraphQL POST requests app.MapPost("/graphql", () => new GraphQLExecutionHttpResult()); await app.RunAsync(); ``` -------------------------------- ### Configure Basic GraphQL Options Source: https://github.com/graphql-dotnet/server/blob/master/README.md Pass a configuration delegate to the UseGraphQL method to customize options like ReadFormOnPost. ```csharp app.UseGraphQL("/graphql", opts => { opts.ReadFormOnPost = true; }); ``` -------------------------------- ### HttpGetValidationRule Definition Source: https://github.com/graphql-dotnet/server/blob/master/tests/ApiApprovalTests/netcoreapp31/GraphQL.Server.Transports.AspNetCore.approved.txt A validation rule to enforce specific constraints for HTTP GET requests in GraphQL. ```csharp public sealed class HttpGetValidationRule : GraphQL.Validation.ValidationRuleBase { public HttpGetValidationRule() { } public override System.Threading.Tasks.ValueTask GetPreNodeVisitorAsync(GraphQL.Validation.ValidationContext context) { } ``` -------------------------------- ### Configure GraphQL with MVC Controller Source: https://github.com/graphql-dotnet/server/blob/master/README.md Set up a controller action to execute GraphQL requests using GraphQLExecutionActionResult for full request handling, including subscriptions. ```csharp public class HomeController : Controller { public IActionResult Index() => new GraphiQLActionResult(opts => { opts.GraphQLEndPoint = "/Home/graphql"; opts.SubscriptionsEndPoint = "/Home/graphql"; }); [HttpGet] [HttpPost] [ActionName("graphql")] public IActionResult GraphQL() => new GraphQLExecutionActionResult(); } ``` -------------------------------- ### Serve GraphiQL IDE with UseGraphQLGraphiQL Source: https://context7.com/graphql-dotnet/server/llms.txt Configures middleware to serve the GraphiQL IDE. Supports custom endpoints, headers, and the `graphql-transport-ws` sub-protocol. ```csharp // Middleware-based app.UseGraphQLGraphiQL("/ui/graphiql", new GraphiQLOptions { GraphQLEndPoint = "/graphql", SubscriptionsEndPoint = "/graphql", HeaderEditorEnabled = true, GraphQLWsSubscriptions = true, // use graphql-transport-ws RequestCredentials = RequestCredentials.SameOrigin, Headers = new() { ["X-Api-Token"] = "my-secret-token", }, }); // Endpoint routing app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapGraphQL("/graphql"); endpoints.MapGraphQLGraphiQL("/"); }); ``` -------------------------------- ### Add Host Application Lifetime Services Source: https://github.com/graphql-dotnet/server/blob/master/README.md Required for ASP.NET Core 2.1 / .NET Framework 4.8 projects. Add this to your `Startup.cs` file. ```csharp services.AddHostApplicationLifetime(); ``` -------------------------------- ### Configure Transport-Specific GraphQL Authorization Source: https://github.com/graphql-dotnet/server/blob/master/README.md Register the GraphQL endpoint multiple times to set distinct authorization options for GET, POST, and WebSocket transports. Use this when different transports require different security levels. ```csharp var app = builder.Build(); app.UseDeveloperExceptionPage(); app.UseGraphQL("/graphql", options => { options.HandleGet = true; options.HandlePost = false; options.HandleWebSockets = false; options.AuthorizationRequired = false; }); app.UseGraphQL("/graphql", options => { options.HandleGet = false; options.HandlePost = true; options.HandleWebSockets = true; options.AuthorizationRequired = true; // require authentication for POST/WebSocket connections }); await app.RunAsync(); ``` -------------------------------- ### GraphQL Subscription Server Implementation Source: https://github.com/graphql-dotnet/server/blob/master/tests/ApiApprovalTests/netcoreapp21+netstandard20/GraphQL.Server.Transports.AspNetCore.approved.txt Implements a subscription server for GraphQL over WebSockets using the graphql-ws protocol. It requires various services for connection handling, execution, serialization, and authentication. ```csharp public class SubscriptionServer : GraphQL.Server.Transports.AspNetCore.WebSockets.BaseSubscriptionServer { public SubscriptionServer(GraphQL.Server.Transports.AspNetCore.WebSockets.IWebSocketConnection connection, GraphQL.Server.Transports.AspNetCore.WebSockets.GraphQLWebSocketOptions options, GraphQL.Server.Transports.AspNetCore.IAuthorizationOptions authorizationOptions, GraphQL.IDocumentExecuter executer, GraphQL.IGraphQLSerializer serializer, Microsoft.Extensions.DependencyInjection.IServiceScopeFactory serviceScopeFactory, GraphQL.Server.Transports.AspNetCore.IUserContextBuilder userContextBuilder, GraphQL.Server.Transports.AspNetCore.WebSockets.IWebSocketAuthenticationService? authenticationService = null) { } protected GraphQL.IDocumentExecuter DocumentExecuter { get; } protected GraphQL.IGraphQLSerializer Serializer { get; } protected Microsoft.Extensions.DependencyInjection.IServiceScopeFactory ServiceScopeFactory { get; } protected System.Collections.Generic.IDictionary? UserContext { get; set; } } ``` -------------------------------- ### Configure GraphQL Playground Middleware Path Source: https://github.com/graphql-dotnet/server/blob/master/docs/migration/migration7.md In v7, the path for `UseGraphQLPlayground` must be specified before the options class. This change applies to all configurations, including default and custom options. ```csharp // v6/v7 app.UseGraphQLPlayground(); ``` ```csharp // v6/v7 app.UseGraphQLPlayground("/"); ``` ```csharp // v6 app.UseGraphQLPlayground(new PlaygroundOptions(), "/"); // v7 app.UseGraphQLPlayground("/", new PlaygroundOptions()); ``` ```csharp // v6 app.UseGraphQLPlayground(new PlaygroundOptions()); // v7 app.UseGraphQLPlayground(options: new PlaygroundOptions()); ``` -------------------------------- ### Altair Middleware Implementation Source: https://github.com/graphql-dotnet/server/blob/master/tests/ApiApprovalTests/netstandard20/GraphQL.Server.Ui.Altair.approved.txt The `AltairMiddleware` class handles incoming HTTP requests for the Altair UI. It requires the next delegate in the pipeline and Altair options for configuration. ```csharp public class AltairMiddleware { public AltairMiddleware(Microsoft.AspNetCore.Http.RequestDelegate next, GraphQL.Server.Ui.Altair.AltairOptions options) { } public System.Threading.Tasks.Task Invoke(Microsoft.AspNetCore.Http.HttpContext httpContext) { } } ``` -------------------------------- ### Serve Voyager Schema Explorer with UseGraphQLVoyager Source: https://context7.com/graphql-dotnet/server/llms.txt Configures middleware to serve the Voyager interactive schema visualization tool. Supports endpoint configuration and request credentials. ```csharp app.UseGraphQLVoyager("/ui/voyager", new VoyagerOptions { GraphQLEndPoint = "/graphql", RequestCredentials = RequestCredentials.Include, Headers = new() { ["Authorization"] = "Bearer my-token", }, }); ``` -------------------------------- ### GraphQL WebSocket Subscription Server Implementation Source: https://github.com/graphql-dotnet/server/blob/master/tests/ApiApprovalTests/netcoreapp31/GraphQL.Server.Transports.AspNetCore.approved.txt Implements the core WebSocket subscription server logic for ASP.NET Core. Handles connection initialization, message processing, request execution, and sending results. ```csharp namespace GraphQL.Server.Transports.AspNetCore.WebSockets.SubscriptionsTransportWs { public class SubscriptionServer : GraphQL.Server.Transports.AspNetCore.WebSockets.BaseSubscriptionServer { public SubscriptionServer(GraphQL.Server.Transports.AspNetCore.WebSockets.IWebSocketConnection connection, GraphQL.Server.Transports.AspNetCore.WebSockets.GraphQLWebSocketOptions options, GraphQL.Server.Transports.AspNetCore.IAuthorizationOptions authorizationOptions, GraphQL.IDocumentExecuter executer, GraphQL.IGraphQLSerializer serializer, Microsoft.Extensions.DependencyInjection.IServiceScopeFactory serviceScopeFactory, GraphQL.Server.Transports.AspNetCore.IUserContextBuilder userContextBuilder, GraphQL.Server.Transports.AspNetCore.WebSockets.IWebSocketAuthenticationService? authenticationService = null) { } protected GraphQL.IDocumentExecuter DocumentExecuter { get; } protected GraphQL.IGraphQLSerializer Serializer { get; } protected Microsoft.Extensions.DependencyInjection.IServiceScopeFactory ServiceScopeFactory { get; } protected System.Collections.Generic.IDictionary? UserContext { get; set; } protected GraphQL.Server.Transports.AspNetCore.IUserContextBuilder UserContextBuilder { get; } public static string SubProtocol { get; } protected override System.Threading.Tasks.ValueTask AuthorizeAsync(GraphQL.Transport.OperationMessage message) { } protected override System.Threading.Tasks.Task ErrorAccessDeniedAsync() { } protected override System.Threading.Tasks.Task ExecuteRequestAsync(GraphQL.Transport.OperationMessage message) { } protected override System.Threading.Tasks.Task OnConnectionAcknowledgeAsync(GraphQL.Transport.OperationMessage message) { } [System.Obsolete("Please use the OnConnectionInitAsync and OnKeepAliveLoopAsync methods instead. Th" + "is method will be removed in a future version of this library.")] protected override System.Threading.Tasks.Task OnConnectionInitAsync(GraphQL.Transport.OperationMessage message, bool smartKeepAlive) { } protected override System.Threading.Tasks.Task OnKeepAliveLoopAsync(System.TimeSpan keepAliveTimeout, GraphQL.Server.Transports.AspNetCore.WebSockets.KeepAliveMode keepAliveMode) { } public override System.Threading.Tasks.Task OnMessageReceivedAsync(GraphQL.Transport.OperationMessage message) { } protected override System.Threading.Tasks.Task OnSendKeepAliveAsync() { } protected virtual System.Threading.Tasks.Task OnStartAsync(GraphQL.Transport.OperationMessage message) { } protected virtual System.Threading.Tasks.Task OnStopAsync(GraphQL.Transport.OperationMessage message) { } protected override System.Threading.Tasks.Task SendCompletedAsync(string id) { } protected override System.Threading.Tasks.Task SendDataAsync(string id, GraphQL.ExecutionResult result) { } protected override System.Threading.Tasks.Task SendErrorResultAsync(string id, GraphQL.ExecutionResult result) { } } } ``` -------------------------------- ### Configure GraphQL Middleware with Schema and Options Source: https://github.com/graphql-dotnet/server/blob/master/tests/ApiApprovalTests/net50/GraphQL.Server.Transports.AspNetCore.approved.txt Integrate the GraphQL middleware into the ASP.NET Core pipeline, specifying the schema type and providing options to configure the middleware. ```csharp public static Microsoft.AspNetCore.Builder.IApplicationBuilder UseGraphQL(this Microsoft.AspNetCore.Builder.IApplicationBuilder builder, string path = "/graphql", System.Action? configureMiddleware = null) where TSchema : GraphQL.Types.ISchema { } ``` -------------------------------- ### GraphQLHttpMiddleware Implementation Source: https://github.com/graphql-dotnet/server/blob/master/tests/ApiApprovalTests/netcoreapp31/GraphQL.Server.Transports.AspNetCore.approved.txt Implementation of the GraphQL HTTP middleware for ASP.NET Core, handling requests and building user contexts. ```csharp public class GraphQLHttpMiddleware : GraphQL.Server.Transports.AspNetCore.GraphQLHttpMiddleware where TSchema : GraphQL.Types.ISchema { public GraphQLHttpMiddleware(Microsoft.AspNetCore.Http.RequestDelegate next, GraphQL.IGraphQLTextSerializer serializer, GraphQL.IDocumentExecuter documentExecuter, Microsoft.Extensions.DependencyInjection.IServiceScopeFactory serviceScopeFactory, GraphQL.Server.Transports.AspNetCore.GraphQLHttpMiddlewareOptions options, Microsoft.Extensions.Hosting.IHostApplicationLifetime hostApplicationLifetime) { } protected override System.Threading.Tasks.ValueTask?> BuildUserContextAsync(Microsoft.AspNetCore.Http.HttpContext context, object? payload) { } ``` -------------------------------- ### Configure GraphQL Middleware with Path Source: https://github.com/graphql-dotnet/server/blob/master/tests/ApiApprovalTests/net50/GraphQL.Server.Transports.AspNetCore.approved.txt Use this extension method to add the GraphQL middleware to the ASP.NET Core pipeline, specifying a custom path. ```csharp public static Microsoft.AspNetCore.Builder.IApplicationBuilder UseGraphQL<[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.None | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicConstructors | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicMethods)] TMiddleware>(this Microsoft.AspNetCore.Builder.IApplicationBuilder builder, Microsoft.AspNetCore.Http.PathString path, params object[] args) where TMiddleware : GraphQL.Server.Transports.AspNetCore.GraphQLHttpMiddleware { } ``` -------------------------------- ### Configure GraphQL WebSocket Options Source: https://context7.com/graphql-dotnet/server/llms.txt Configure WebSocket-specific options for the GraphQL middleware, including connection initialization timeouts, disconnection behavior, keep-alive settings, and supported sub-protocols. ```csharp app.UseGraphQL("/graphql", opts => { var ws = opts.WebSockets; // Require connection init within 10 s ws.ConnectionInitWaitTimeout = TimeSpan.FromSeconds(10); // Graceful teardown timeout ws.DisconnectionTimeout = TimeSpan.FromSeconds(10); // Keep-alive: bidirectional ping/pong every 15 s (graphql-transport-ws only) ws.KeepAliveTimeout = TimeSpan.FromSeconds(15); ws.KeepAliveMode = KeepAliveMode.TimeoutWithPayload; // Only allow graphql-transport-ws when using TimeoutWithPayload ws.SupportedWebSocketSubProtocols = [GraphQLWs.SubscriptionServer.SubProtocol]; // Disconnect a subscription when an OnError event is fired ws.DisconnectAfterErrorEvent = true; // Disconnect a subscription on any GraphQL error during subscription ws.DisconnectAfterAnyError = false; }); // KeepAliveMode values: // KeepAliveMode.Default / Timeout — send ping when no message received within timeout // KeepAliveMode.Interval — send ping at fixed interval regardless of activity // KeepAliveMode.TimeoutWithPayload — bidirectional ping/pong; closes dead connections ``` -------------------------------- ### GraphQLHttpMiddlewareOptions Configuration Source: https://github.com/graphql-dotnet/server/blob/master/tests/ApiApprovalTests/netcoreapp31/GraphQL.Server.Transports.AspNetCore.approved.txt Configure options for the GraphQL HTTP middleware, including request handling and batched requests. ```csharp public class GraphQLHttpMiddlewareOptions { public bool EnableBatchedRequests { get; set; } public bool ExecuteBatchedRequestsInParallel { get; set; } public bool HandleGet { get; set; } public bool HandlePost { get; set; } public bool HandleWebSockets { get; set; } public int? MaximumFileCount { get; set; } public long? MaximumFileSize { get; set; } public bool ReadExtensionsFromQueryString { get; set; } public bool ReadFormOnPost { get; set; } public bool ReadQueryStringOnPost { get; set; } public bool ReadVariablesFromQueryString { get; set; } public bool? ValidationErrorsReturnBadRequest { get; set; } public GraphQL.Server.Transports.AspNetCore.WebSockets.GraphQLWebSocketOptions WebSockets { get; set; } } ``` -------------------------------- ### Configure WebSocket Authentication Service Source: https://github.com/graphql-dotnet/server/blob/master/README.md Sets up GraphQL with WebSocket authentication, allowing authorization via the ConnectionInit WebSocket message. Requires a custom authentication service. ```csharp builder.Services.AddGraphQL(b => b .AddAutoSchema() .AddSystemTextJson() .AddAuthorizationRule() // not required for endpoint authorization .AddWebSocketAuthentication()); app.UseGraphQL("/graphql", config => { // require that the user be authenticated config.AuthorizationRequired = true; }); class MyAuthService : IWebSocketAuthenticationService { private readonly IGraphQLSerializer _serializer; public MyAuthService(IGraphQLSerializer serializer) { _serializer = serializer; } public async ValueTask AuthenticateAsync(IWebSocketConnection connection, OperationMessage operationMessage) { // read payload of ConnectionInit message and look for an "Authorization" entry that starts with "Bearer " var payload = _serializer.ReadNode(operationMessage.Payload); if ((payload?.TryGetValue("Authorization", out var value) ?? false) && value is string valueString) { var user = ParseToken(valueString); if (user != null) { // set user and indicate authentication was successful connection.HttpContext.User = user; return true; } } return false; // authentication failed } private ClaimsPrincipal? ParseToken(string authorizationHeaderValue) { // parse header value and return user, or null if unable } } ``` -------------------------------- ### UserContextBuilder Source: https://github.com/graphql-dotnet/server/blob/master/tests/ApiApprovalTests/netcoreapp31/GraphQL.Server.Transports.AspNetCore.approved.txt A generic implementation of IUserContextBuilder. ```APIDOC ## UserContextBuilder ### Description A generic implementation of `IUserContextBuilder` that allows for custom user context creation. ### Constructors - **UserContextBuilder(Func> func)**: Initializes with an asynchronous function. - **UserContextBuilder(Func func)**: Initializes with a synchronous function. - **UserContextBuilder(Func> func)**: Initializes with an asynchronous function including a payload. - **UserContextBuilder(Func func)**: Initializes with a synchronous function including a payload. ### Methods - **BuildUserContextAsync(HttpContext context, object? payload)**: Asynchronously builds the user context. ``` -------------------------------- ### GraphQL Minimal API and MVC Route Handlers Source: https://context7.com/graphql-dotnet/server/llms.txt Implement GraphQL endpoints using Minimal APIs with `MapGet`/`MapPost` and `GraphQLExecutionHttpResult`, or within MVC controller actions using `GraphQLExecutionActionResult`. Supports options for request execution. ```csharp // Minimal API (Program.cs) var app = builder.Build(); app.UseWebSockets(); app.MapGet("/graphql", () => new GraphQLExecutionHttpResult()); app.MapPost("/graphql", () => new GraphQLExecutionHttpResult()); // With options app.MapPost("/graphql-strict", () => new GraphQLExecutionHttpResult(opts => { opts.EnableBatchedRequests = false; opts.AuthorizationRequired = true; })); await app.RunAsync(); // ───────────────────────────────────────────────────────────────────────────── // MVC Controller Action (HomeController.cs) public class HomeController : Controller { [HttpGet, HttpPost, ActionName("graphql")] public IActionResult GraphQL() => new GraphQLExecutionActionResult(); } // Azure Function (GraphQL.cs) public static class GraphQLFunction { [FunctionName("GraphQL")] public static IActionResult Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequest req) => new GraphQLExecutionActionResult(); } ``` -------------------------------- ### Using GraphQL Middleware Source: https://github.com/graphql-dotnet/server/blob/master/tests/ApiApprovalTests/net60+net80/GraphQL.Server.Transports.AspNetCore.approved.txt Configure the GraphQL middleware to handle requests at a specified path. This method allows for custom configuration of the middleware options. ```APIDOC ## UseGraphQL (Middleware) ### Description Configures the application to use the GraphQL HTTP middleware, enabling GraphQL requests to be handled at a specific path. ### Method `UseGraphQL` (extension method on `IApplicationBuilder`) ### Parameters - `builder` (`IApplicationBuilder`): The application builder. - `path` (`PathString` or `string`): The URL path for the GraphQL endpoint (e.g., "/graphql"). - `configureMiddleware` (`Action`): An optional delegate to configure middleware options. ### Example ```csharp app.UseGraphQL("/graphql"); app.UseGraphQL("/graphql", options => { // Configure options here }); ``` ``` -------------------------------- ### Add User Context Builder (Class Form) Source: https://context7.com/graphql-dotnet/server/llms.txt Implement IUserContextBuilder interface to create a reusable class for building user context. Useful for complex context creation logic. ```csharp // Class form — implements IUserContextBuilder public class MyUserContextBuilder : IUserContextBuilder { public async ValueTask?> BuildUserContextAsync( HttpContext context, object? payload) { // payload is non-null for WebSocket connections (the ConnectionInit payload) var userService = context.RequestServices.GetRequiredService(); return new Dictionary { ["user"] = await userService.GetUserAsync(context.User), }; } } builder.Services.AddGraphQL(b => b .AddAutoSchema() .AddSystemTextJson() .AddUserContextBuilder()); ``` -------------------------------- ### Configure Multiple GraphQL Schemas Source: https://github.com/graphql-dotnet/server/blob/master/README.md Map different GraphQL schemas to distinct URL paths using generic builder methods. This allows for serving multiple schemas from a single application instance. ```csharp var app = builder.Build(); app.UseDeveloperExceptionPage(); app.UseGraphQL("/dogs/graphql"); app.UseGraphQL("/cats/graphql"); await app.RunAsync(); ``` -------------------------------- ### GraphiQLOptions Source: https://github.com/graphql-dotnet/server/blob/master/tests/ApiApprovalTests/netstandard20/GraphQL.Server.Ui.GraphiQL.approved.txt Configuration options for the GraphiQL UI. ```APIDOC ## GraphiQLOptions ### Description Provides configuration settings for customizing the GraphiQL interface. ### Properties - **ExplorerExtensionEnabled** (bool) - Obsolete. This property has no effect and will be removed in a future version. - **GraphQLEndPoint** (string) - The endpoint for GraphQL requests. - **GraphQLWsSubscriptions** (bool) - Enables or disables WebSocket subscriptions for GraphQL. - **HeaderEditorEnabled** (bool) - Enables or disables the header editor in GraphiQL. - **Headers** (Dictionary) - A dictionary of headers to be sent with requests. - **IndexStream** (Func) - A function to provide a custom stream for the GraphiQL index page. - **PostConfigure** (Func) - A function to configure the GraphiQL options after initialization. - **RequestCredentials** (RequestCredentials) - Specifies the credentials to be sent with requests. - **SubscriptionsEndPoint** (string) - The endpoint for WebSocket subscriptions. ``` -------------------------------- ### UseGraphQL with Middleware and Path String Source: https://github.com/graphql-dotnet/server/blob/master/tests/ApiApprovalTests/netcoreapp21+netstandard20/GraphQL.Server.Transports.AspNetCore.approved.txt Configures the GraphQL endpoint using a specific middleware type and a string path, with additional arguments. ```APIDOC ## UseGraphQL ### Description Configures the GraphQL endpoint using a specific middleware type and a string path. Allows for additional arguments to be passed to the middleware. ### Method Signature public static Microsoft.AspNetCore.Builder.IApplicationBuilder UseGraphQL(this Microsoft.AspNetCore.Builder.IApplicationBuilder builder, string path = "/graphql", params object[] args) ### Type Parameters * `TMiddleware`: The type of the GraphQL middleware to use, must inherit from `GraphQL.Server.Transports.AspNetCore.GraphQLHttpMiddleware`. ### Parameters * `builder` (Microsoft.AspNetCore.Builder.IApplicationBuilder) - The application builder. * `path` (string) - The path for the GraphQL endpoint. Defaults to "/graphql". * `args` (params object[]) - Additional arguments to pass to the middleware. ``` -------------------------------- ### Include GraphQL UI Middleware Source: https://github.com/graphql-dotnet/server/blob/master/README.md Add middleware for various GraphQL UIs like Altair, GraphiQL, Playground, and Voyager to your application pipeline. ```csharp app.UseGraphQLAltair(); app.UseGraphQLGraphiQL(); app.UseGraphQLPlayground(); // deprecated app.UseGraphQLVoyager(); ``` ```csharp endpoints.MapGraphQLAltair(); endpoints.MapGraphQLGraphiQL(); endpoints.MapGraphQLPlayground(); // deprecated endpoints.MapGraphQLVoyager(); ``` -------------------------------- ### Configure GraphQL with Endpoint Routing (Same URL) Source: https://github.com/graphql-dotnet/server/blob/master/README.md When UI and GraphQL share the same URL, use MapGraphQL within UseEndpoints and ensure UI middleware precedes it. ```csharp var app = builder.Build(); app.UseDeveloperExceptionPage(); app.UseWebSockets(); app.UseRouting(); app.UseGraphQLVoyager("/graphql"); app.UseEndpoints(endpoints => { endpoints.MapGraphQL("/graphql"); }); await app.RunAsync(); ``` -------------------------------- ### GraphQLHttpMiddlewareOptions Source: https://github.com/graphql-dotnet/server/blob/master/tests/ApiApprovalTests/netcoreapp31/GraphQL.Server.Transports.AspNetCore.approved.txt Configuration options for the GraphQL HTTP Middleware. ```APIDOC ## GraphQLHttpMiddlewareOptions ### Description Provides configuration settings for the `GraphQLHttpMiddleware`, including authentication, authorization, and CSRF protection. ### Properties * **AuthenticationSchemes** (`System.Collections.Generic.List`) - A list of authentication schemes to be used. * **AuthorizationRequired** (`bool`) - A flag indicating whether authorization is required for all requests. * **AuthorizedPolicy** (`string?`) - The name of the authorization policy required for requests. * **AuthorizedRoles** (`System.Collections.Generic.List`) - A list of roles that are authorized to access the endpoint. * **CsrfProtectionEnabled** (`bool`) - A flag to enable or disable CSRF protection. * **CsrfProtectionHeaders** (`System.Collections.Generic.List`) - A list of headers to check for CSRF protection. * **DefaultResponseContentType** (`Microsoft.Net.Http.Headers.MediaTypeHeaderValue`) - The default `Content-Type` header for responses. ``` -------------------------------- ### IUserContextBuilder Interface Source: https://github.com/graphql-dotnet/server/blob/master/tests/ApiApprovalTests/netcoreapp31/GraphQL.Server.Transports.AspNetCore.approved.txt Interface for building a user context asynchronously. ```csharp public interface IUserContextBuilder { System.Threading.Tasks.ValueTask?> BuildUserContextAsync(Microsoft.AspNetCore.Http.HttpContext context, object? payload); } ``` -------------------------------- ### Altair Options Configuration Source: https://github.com/graphql-dotnet/server/blob/master/tests/ApiApprovalTests/netstandard20/GraphQL.Server.Ui.Altair.approved.txt Configure Altair UI settings using the `AltairOptions` class. This includes setting the GraphQL endpoint, custom headers, and subscription details. ```csharp public class AltairOptions { public AltairOptions() { } public string GraphQLEndPoint { get; set; } public System.Collections.Generic.Dictionary? Headers { get; set; } public System.Func IndexStream { get; set; } public System.Func PostConfigure { get; set; } public System.Collections.Generic.Dictionary? Settings { get; set; } public string SubscriptionsEndPoint { get; set; } public System.Collections.Generic.Dictionary? SubscriptionsPayload { get; set; } } ``` -------------------------------- ### Configure GraphQL Middleware with Custom Middleware Source: https://github.com/graphql-dotnet/server/blob/master/tests/ApiApprovalTests/net50/GraphQL.Server.Transports.AspNetCore.approved.txt Add a custom GraphQL middleware to the ASP.NET Core pipeline, allowing for advanced customization and argument passing. ```csharp public static Microsoft.AspNetCore.Builder.IApplicationBuilder UseGraphQL<[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.None | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicConstructors | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicMethods)] TMiddleware>(this Microsoft.AspNetCore.Builder.IApplicationBuilder builder, string path = "/graphql", params object[] args) where TMiddleware : GraphQL.Server.Transports.AspNetCore.GraphQLHttpMiddleware { } ``` -------------------------------- ### GraphiQLApplicationBuilderExtensions Source: https://github.com/graphql-dotnet/server/blob/master/tests/ApiApprovalTests/netstandard20/GraphQL.Server.Ui.GraphiQL.approved.txt Provides an extension method to easily integrate the GraphiQL UI into an ASP.NET Core application pipeline. ```APIDOC ## UseGraphQLGraphiQL ### Description Adds the GraphiQL middleware to the application's HTTP request pipeline. ### Method `UseGraphQLGraphiQL` ### Parameters #### Path Parameters - **app** (IApplicationBuilder) - Required - The application builder. - **path** (string) - Optional - The path to mount the GraphiQL UI. Defaults to "/ui/graphiql". - **options** (GraphiQLOptions) - Optional - Configuration options for GraphiQL. ``` -------------------------------- ### GraphQL HTTP Middleware Methods Source: https://github.com/graphql-dotnet/server/blob/master/tests/ApiApprovalTests/netcoreapp31/GraphQL.Server.Transports.AspNetCore.approved.txt Provides methods for handling GraphQL requests over HTTP and WebSockets. Includes logic for building user context, processing messages, and executing requests. ```csharp protected virtual System.Collections.Generic.IEnumerable SupportedWebSocketSubProtocols { get; } ``` ```csharp protected virtual System.Threading.Tasks.ValueTask?> BuildUserContextAsync(Microsoft.AspNetCore.Http.HttpContext context, object? payload) { } ``` ```csharp protected virtual GraphQL.Server.Transports.AspNetCore.WebSockets.IOperationMessageProcessor CreateMessageProcessor(GraphQL.Server.Transports.AspNetCore.WebSockets.IWebSocketConnection webSocketConnection, string subProtocol) { } ``` ```csharp protected virtual GraphQL.Server.Transports.AspNetCore.WebSockets.IWebSocketConnection CreateWebSocketConnection(Microsoft.AspNetCore.Http.HttpContext httpContext, System.Net.WebSockets.WebSocket webSocket, System.Threading.CancellationToken cancellationToken) { } ``` ```csharp protected virtual System.Threading.Tasks.Task ExecuteRequestAsync(Microsoft.AspNetCore.Http.HttpContext context, GraphQL.Transport.GraphQLRequest? request, System.IServiceProvider serviceProvider, System.Collections.Generic.IDictionary? userContext) { } ``` ```csharp protected virtual System.Threading.Tasks.Task ExecuteScopedRequestAsync(Microsoft.AspNetCore.Http.HttpContext context, GraphQL.Transport.GraphQLRequest? request, System.Collections.Generic.IDictionary? userContext) { } ``` ```csharp protected virtual System.Threading.Tasks.ValueTask HandleAuthorizeAsync(Microsoft.AspNetCore.Http.HttpContext context, Microsoft.AspNetCore.Http.RequestDelegate next) { } ``` ```csharp protected virtual System.Threading.Tasks.ValueTask HandleAuthorizeWebSocketConnectionAsync(Microsoft.AspNetCore.Http.HttpContext context, Microsoft.AspNetCore.Http.RequestDelegate next) { } ``` ```csharp protected virtual System.Threading.Tasks.Task HandleBatchRequestAsync(Microsoft.AspNetCore.Http.HttpContext context, Microsoft.AspNetCore.Http.RequestDelegate next, System.Collections.Generic.IList gqlRequests) { } ``` ```csharp protected virtual System.Threading.Tasks.Task HandleBatchedRequestsNotSupportedAsync(Microsoft.AspNetCore.Http.HttpContext context, Microsoft.AspNetCore.Http.RequestDelegate next) { } ``` -------------------------------- ### Migrate Separate Subscription Endpoint Source: https://github.com/graphql-dotnet/server/blob/master/docs/migration/migration7.md Configure separate endpoints for GraphQL and WebSockets by adjusting the HandleWebSockets, HandleGet, and HandlePost options. ```csharp // v6 app.UseGraphQL("/graphql"); app.UseGraphQLWebSockets("/graphqlsubscription"); // v7 app.UseGraphQL("/graphql", o => o.HandleWebSockets = false); app.UseGraphQL("/graphqlsubscription", o => { o.HandleGet = false; o.HandlePost = false; }); ``` -------------------------------- ### Map GraphQL Endpoint with Schema Source: https://github.com/graphql-dotnet/server/blob/master/tests/ApiApprovalTests/net50/GraphQL.Server.Transports.AspNetCore.approved.txt Map the GraphQL endpoint using a specific schema and configure the middleware options. ```csharp public static Microsoft.AspNetCore.Builder.GraphQLEndpointConventionBuilder MapGraphQL(this Microsoft.AspNetCore.Routing.IEndpointRouteBuilder endpoints, string pattern = "graphql", System.Action? configureMiddleware = null) where TSchema : GraphQL.Types.ISchema { } ``` -------------------------------- ### Map GraphQL Endpoint with Custom Middleware Source: https://github.com/graphql-dotnet/server/blob/master/tests/ApiApprovalTests/net50/GraphQL.Server.Transports.AspNetCore.approved.txt Map the GraphQL endpoint using a custom middleware and pass additional arguments for configuration. ```csharp public static Microsoft.AspNetCore.Builder.GraphQLEndpointConventionBuilder MapGraphQL<[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.None | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicConstructors | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicMethods)] TMiddleware>(this Microsoft.AspNetCore.Routing.IEndpointRouteBuilder endpoints, string pattern = "graphql", params object[] args) where TMiddleware : GraphQL.Server.Transports.AspNetCore.GraphQLHttpMiddleware { } ``` -------------------------------- ### GraphiQLMiddleware Source: https://github.com/graphql-dotnet/server/blob/master/tests/ApiApprovalTests/netstandard20/GraphQL.Server.Ui.GraphiQL.approved.txt Middleware for serving the GraphiQL UI. ```APIDOC ## GraphiQLMiddleware ### Description Handles incoming HTTP requests and serves the GraphiQL interface. ### Constructor `GraphiQLMiddleware(RequestDelegate next, GraphiQLOptions options)` ### Method `Invoke(HttpContext httpContext)` ### Parameters #### Path Parameters - **next** (RequestDelegate) - Required - The next middleware in the pipeline. - **options** (GraphiQLOptions) - Required - Configuration options for GraphiQL. ``` -------------------------------- ### UseGraphQL with Schema and Path String Source: https://github.com/graphql-dotnet/server/blob/master/tests/ApiApprovalTests/netcoreapp21+netstandard20/GraphQL.Server.Transports.AspNetCore.approved.txt Configures the GraphQL endpoint using a schema type and a string path, with optional middleware configuration. ```APIDOC ## UseGraphQL ### Description Configures the GraphQL endpoint using a schema type and a string path. Allows for optional configuration of the middleware options. ### Method Signature public static Microsoft.AspNetCore.Builder.IApplicationBuilder UseGraphQL(this Microsoft.AspNetCore.Builder.IApplicationBuilder builder, string path = "/graphql", System.Action? configureMiddleware = null) ### Type Parameters * `TSchema`: The type of the GraphQL schema to use, must implement `GraphQL.Types.ISchema`. ### Parameters * `builder` (Microsoft.AspNetCore.Builder.IApplicationBuilder) - The application builder. * `path` (string) - The path for the GraphQL endpoint. Defaults to "/graphql". * `configureMiddleware` (System.Action?) - An optional action to configure the middleware options. ``` -------------------------------- ### Register Multiple GraphQL Schemas with UseGraphQL Source: https://context7.com/graphql-dotnet/server/llms.txt Register two distinct GraphQL schemas, CatsSchema and DogsSchema, each accessible at a separate URL path. Ensure to add necessary services like AutoClrMappings and SystemTextJson. ```csharp // Program.cs — two schemas at separate URL paths builder.Services.AddGraphQL(b => b .AddSchema() .AddSchema() .AddAutoClrMappings() .AddSystemTextJson()); var app = builder.Build(); app.UseWebSockets(); app.UseGraphQL("/cats/graphql"); app.UseGraphQL("/dogs/graphql"); app.UseGraphQLGraphiQL("/cats/ui/graphiql", new GraphiQLOptions { GraphQLEndPoint = "../graphql", SubscriptionsEndPoint = "../graphql" }); app.UseGraphQLGraphiQL("/dogs/ui/graphiql", new GraphiQLOptions { GraphQLEndPoint = "../graphql", SubscriptionsEndPoint = "../graphql" }); await app.RunAsync(); ``` -------------------------------- ### GraphQLHttpMiddleware.InvokeAsync Source: https://github.com/graphql-dotnet/server/blob/master/tests/ApiApprovalTests/netcoreapp31/GraphQL.Server.Transports.AspNetCore.approved.txt The main entry point for the middleware, processing an incoming HTTP context. ```APIDOC ## InvokeAsync ### Description Processes an incoming `HttpContext` to handle GraphQL requests. ### Method `public virtual System.Threading.Tasks.Task InvokeAsync(Microsoft.AspNetCore.Http.HttpContext context)` ### Parameters * **context** (`Microsoft.AspNetCore.Http.HttpContext`) - The HTTP context to process. ``` -------------------------------- ### SubscriptionServer Methods Source: https://github.com/graphql-dotnet/server/blob/master/tests/ApiApprovalTests/netcoreapp21+netstandard20/GraphQL.Server.Transports.AspNetCore.approved.txt Manages the GraphQL subscription server over WebSockets, handling client subscriptions and message routing. ```APIDOC ## SubscriptionServer ### Description Manages the GraphQL subscription server logic over WebSockets, enabling real-time data delivery. ### Methods #### Constructor Initializes a new instance of the `SubscriptionServer` class with necessary dependencies for WebSocket communication and GraphQL execution. #### DocumentExecuter Gets the `IDocumentExecuter` used for executing GraphQL queries. #### Serializer Gets the `IGraphQLSerializer` used for serializing and deserializing GraphQL messages. #### ServiceScopeFactory Gets the `IServiceScopeFactory` for creating service scopes. #### UserContext Gets or sets the user context for the current connection. ``` -------------------------------- ### GraphiQLOptions Source: https://github.com/graphql-dotnet/server/blob/master/tests/ApiApprovalTests/net80+netcoreapp31/GraphQL.Server.Ui.GraphiQL.approved.txt Configuration options for the GraphiQL UI, including GraphQL and subscription endpoints, headers, and other UI-specific settings. ```APIDOC ## GraphiQLOptions ### Description Configuration options for the GraphiQL UI, including GraphQL and subscription endpoints, headers, and other UI-specific settings. ### Constructors - `GraphiQLOptions()` ### Properties - `bool ExplorerExtensionEnabled` (Obsolete) - `string GraphQLEndPoint` - `bool GraphQLWsSubscriptions` - `bool HeaderEditorEnabled` - `System.Collections.Generic.Dictionary? Headers` - `System.Func IndexStream` - `System.Func PostConfigure` - `GraphQL.Server.Ui.GraphiQL.RequestCredentials RequestCredentials` - `string SubscriptionsEndPoint` ``` -------------------------------- ### Serve Altair GraphQL Client with UseGraphQLAltair Source: https://context7.com/graphql-dotnet/server/llms.txt Provides middleware to serve the Altair GraphQL client UI. Allows configuration of endpoints, headers, and subscription payloads. ```csharp app.UseGraphQLAltair("/ui/altair", new AltairOptions { GraphQLEndPoint = "/graphql", SubscriptionsEndPoint = "/graphql", Headers = new() { ["X-Api-Token"] = "my-secret-token", }, SubscriptionsPayload = new() { ["Authorization"] = "Bearer ", }, Settings = new() { ["theme"] = "dark", ["language"] = "en-US", }, }); ``` -------------------------------- ### Configure Response Compression for GraphQL Source: https://github.com/graphql-dotnet/server/blob/master/README.md Enable response compression for your application, including the 'application/graphql-response+json' MIME type. Be aware of potential security risks over HTTPS. ```csharp // add and configure the service builder.Services.AddResponseCompression(options => { options.EnableForHttps = true; // may lead to CRIME and BREACH attacks options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Append("application/graphql-response+json"); }) // place this first/early in the pipeline app.UseResponseCompression(); ``` -------------------------------- ### IUserContextBuilder Source: https://github.com/graphql-dotnet/server/blob/master/tests/ApiApprovalTests/netcoreapp31/GraphQL.Server.Transports.AspNetCore.approved.txt Interface for building user contexts in GraphQL. ```APIDOC ## IUserContextBuilder ### Description Interface for building user contexts for GraphQL requests. ### Methods - **BuildUserContextAsync(HttpContext context, object? payload)**: Asynchronously builds the user context. ``` -------------------------------- ### AltairOptions Source: https://github.com/graphql-dotnet/server/blob/master/tests/ApiApprovalTests/netstandard20/GraphQL.Server.Ui.Altair.approved.txt Configuration options for customizing the Altair GraphQL UI. ```APIDOC ## AltairOptions ### Description Provides configuration settings for the Altair GraphQL UI. ### Properties - **GraphQLEndPoint** (string): The URL endpoint for your GraphQL API. - **Headers** (Dictionary?, optional): Custom headers to be included in requests to the GraphQL endpoint. - **IndexStream** (Func, optional): A function to provide a custom stream for the index HTML page. - **PostConfigure** (Func, optional): A function to perform post-configuration on the index HTML content. - **Settings** (Dictionary?, optional): Additional settings for the Altair UI. - **SubscriptionsEndPoint** (string, optional): The URL endpoint for GraphQL subscriptions. - **SubscriptionsPayload** (Dictionary?, optional): Payload to be sent with subscription requests. ```