GraphQL.Server.Ui.GraphiQL 8.3.3

dotnet add package GraphQL.Server.Ui.GraphiQL --version 8.3.3
                    
NuGet\Install-Package GraphQL.Server.Ui.GraphiQL -Version 8.3.3
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="GraphQL.Server.Ui.GraphiQL" Version="8.3.3" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="GraphQL.Server.Ui.GraphiQL" Version="8.3.3" />
                    
Directory.Packages.props
<PackageReference Include="GraphQL.Server.Ui.GraphiQL" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add GraphQL.Server.Ui.GraphiQL --version 8.3.3
                    
#r "nuget: GraphQL.Server.Ui.GraphiQL, 8.3.3"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package GraphQL.Server.Ui.GraphiQL@8.3.3
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=GraphQL.Server.Ui.GraphiQL&version=8.3.3
                    
Install as a Cake Addin
#tool nuget:?package=GraphQL.Server.Ui.GraphiQL&version=8.3.3
                    
Install as a Cake Tool

ASP.NET Core GraphQL Server driven by GraphQL.NET

License codecov Nuget Nuget GitHub Release Date GitHub commits since latest release (by date) GitHub contributors Size

GraphQL ASP.NET Core server on top of GraphQL.NET. HTTP transport compatible with the GraphQL over HTTP draft specification. WebSocket transport compatible with both subscriptions-transport-ws and graphql-ws subscription protocols. The transport format of all messages is supposed to be JSON.

Provides the following packages:

Package Downloads Version Description
GraphQL.Server.All Nuget Nuget Includes all the packages below, plus the GraphQL.DataLoader and GraphQL.MemoryCache packages
GraphQL.Server.Transports.AspNetCore Nuget Nuget Provides GraphQL over HTTP/WebSocket server support on top of ASP.NET Core, plus authorization rule support
GraphQL.Server.Ui.Altair Nuget Nuget Provides Altair UI middleware
GraphQL.Server.Ui.Playground ⚠️ Nuget Nuget Provides Playground UI middleware (deprecated)
GraphQL.Server.Ui.GraphiQL Nuget Nuget Provides GraphiQL UI middleware
GraphQL.Server.Ui.Voyager Nuget Nuget Provides Voyager UI middleware

You can install the latest stable versions via NuGet. Also you can get all preview versions from GitHub Packages. Note that GitHub requires authentication to consume the feed. See more information here.

⚠️ When upgrading from prior versions, please remove references to these old packages ⚠️
GraphQL.Server.Core
GraphQL.Server.Authentication.AspNetCore
GraphQL.Server.Transports.AspNetCore.NewtonsoftJson
GraphQL.Server.Transports.AspNetCore.SystemTextJson
GraphQL.Server.Transports.Subscriptions.Abstractions
GraphQL.Server.Transports.Subscriptions.WebSockets
GraphQL.Server.Transports.WebSocktes

Description

This package is designed for ASP.NET Core (2.1 through 9.0) to facilitate easy set-up of GraphQL requests over HTTP. The code is designed to be used as middleware within the ASP.NET Core pipeline, serving GET, POST or WebSocket requests. GET requests process requests from the query string. POST requests can be in the form of JSON requests, form submissions, or raw GraphQL strings. Form submissions either accepts query, operationName, variables and extensions parameters, or operations and map parameters along with file uploads as defined in the GraphQL multipart request spec. WebSocket requests can use the graphql-ws or graphql-transport-ws WebSocket sub-protocol, as defined in the apollographql/subscriptions-transport-ws and enisdenjo/graphql-ws repositories, respectively.

The middleware can be configured through the IApplicationBuilder or IEndpointRouteBuilder builder interfaces. Alternatively, route handlers (such as MapGet and MapPost) can return a GraphQLExecutionHttpResult for direct GraphQL execution, or ExecutionResultHttpResult for returning pre-executed GraphQL responses. Similarly, GraphQLExecutionActionResult and ExecutionResultActionResult classes can be used to return GraphQL responses from controller actions.

Authorization is also supported with the included AuthorizationValidationRule. It will scan GraphQL documents and validate that the schema and all referenced output graph types, fields of output graph types, and query arguments meet the specified policy and/or roles held by the authenticated user within the ASP.NET Core authorization framework. It does not validate any policies or roles specified for input graph types, fields of input graph types, or directives. It skips validations for fields or fragments that are marked with the @skip or @include directives.

Migration from older version

Configuration

Typical configuration with HTTP middleware

First add either the GraphQL.Server.All nuget package or the GraphQL.Server.Transports.AspNetCore nuget package to your application. Referencing the "all" package will include the UI middleware packages. These packages depend on GraphQL version 8.2.1 or later.

Then update your Program.cs or Startup.cs to configure GraphQL, registering the schema and the serialization engine as a minimum. Configure WebSockets and GraphQL in the HTTP pipeline by calling UseWebSockets and UseGraphQL at the appropriate point. Finally, you may also include some UI middleware for easy testing of your GraphQL endpoint by calling UseGraphQLGraphiQL or a similar method at the appropriate point.

Below is a complete sample of a .NET 6 console app that hosts a GraphQL endpoint at http://localhost:5000/graphql:

Project file
<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="GraphQL.Server.All" Version="7.0.0" />
  </ItemGroup>

</Project>
Program.cs file
using GraphQL;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddGraphQL(b => b
    .AddAutoSchema<Query>()  // 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();
Schema
public class Query
{
    public static string Hero() => "Luke Skywalker";
}
Sample request url
http://localhost:5000/graphql?query={hero}
Sample response
{"data":{"hero":"Luke Skywalker"}}

Basic options

By default, the middleware will be installed with these configurable options:

  • GET, POST, and WebSocket requests are all enabled
  • Form content types are disabled, and cross-site request forgery (CSRF) protection is enabled
  • There are no authentication or authorization requirements
  • The default response content type is application/graphql-response+json
  • The middleware will use the default schema instance

To configure these options, pass a confiuguration delegate to the UseGraphQL method as demonstrated below:

app.UseGraphQL("/graphql", opts => {
    opts.ReadFormOnPost = true;
});

Configuration of these options and more are further described below in this document.

Configuration with endpoint routing

To use endpoint routing, call MapGraphQL from inside the endpoint configuration builder rather than UseGraphQL on the application builder. See below for the sample of the application builder code:

var app = builder.Build();
app.UseDeveloperExceptionPage();
app.UseWebSockets();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
    endpoints.MapGraphQL("graphql");
    endpoints.MapGraphQLVoyager("ui/voyager");
});
await app.RunAsync();

Using endpoint routing is particularly useful when you want to select a specific CORS configuration for the GraphQL endpoint. See the CORS section below for a sample.

Please note that when using endpoint routing, you cannot use WebSocket connections while a UI package is also configured at the same URL. You will need to use a different URL for the UI package, or use UI middleware prior to endpoint routing. So long as different URLs are used, there are no issues. Below is a sample when the UI and GraphQL reside at the same URL:

var app = builder.Build();
app.UseDeveloperExceptionPage();
app.UseWebSockets();
app.UseRouting();
app.UseGraphQLVoyager("/graphql");
app.UseEndpoints(endpoints =>
{
    endpoints.MapGraphQL("/graphql");
});
await app.RunAsync();

Configuration with route handlers (.NET 6+)

Although not recommended, you may set up route handlers to execute GraphQL requests using MapGet and MapPost that return an IResult. You will not need UseGraphQL or MapGraphQL in the application startup. Note that GET must be mapped to support WebSocket connections, as WebSocket connections upgrade from HTTP GET requests.

Using GraphQLExecutionHttpResult
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();
Using ExecutionResultHttpResult
app.MapPost("/graphql", async (HttpContext context, IDocumentExecuter<ISchema> documentExecuter, IGraphQLSerializer serializer) =>
{
    var request = await serializer.ReadAsync<GraphQLRequest>(context.Request.Body, context.RequestAborted);
    var opts = new ExecutionOptions
    {
        Query = request?.Query,
        DocumentId = request?.DocumentId,
        Variables = request?.Variables,
        Extensions = request?.Extensions,
        CancellationToken = context.RequestAborted,
        RequestServices = context.RequestServices,
        User = context.User,
    };

    return new ExecutionResultHttpResult(await documentExecuter.ExecuteAsync(opts));
});

Configuration with a MVC controller

Although not recommended, you may set up a controller action to execute GraphQL requests. You will not need UseGraphQL or MapGraphQL in the application startup. You may use GraphQLExecutionActionResult to let the middleware handle the entire parsing and execution of the request, including subscription requests over WebSocket connections, or you can execute the request yourself, only using ExecutionResultActionResult to serialize the result.

You can also reference the UI projects to display a GraphQL user interface as shown below.

Using GraphQLExecutionActionResult