ASP.NET Core GraphQL 服务器
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:
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.
| :warning: When upgrading from prior versions, please remove references to these old packages :warning: |
|---|
| 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 |
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.
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:
net6.0
enable
enable
…public class Query
{
public static string Hero() => "Luke Skywalker";
}http://localhost:5000/graphql?query={hero}{"data":{"hero":"Luke Skywalker"}}By default, the middleware will be installed with these configurable options:
application/graphql-response+jsonTo 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.
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();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.
GraphQLExecutionHttpResultvar 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();ExecutionResultHttpResult…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.
GraphQLExecutionActionResultpublic 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 Grap暂无开放 Issues,或尚未同步最近议题。