百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
S

server

> 后端框架
开源

ASP.NET Core GraphQL 服务器

603 stars0 点赞0 次浏览
访问官网GitHub

工具介绍

ASP.NET Core GraphQL 服务器

ASP.NET Core GraphQL Server driven by GraphQL.NET

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 Includes all the packages below, plus the GraphQL.DataLoader and GraphQL.MemoryCache packages
GraphQL.Server.Transports.AspNetCore Provides GraphQL over HTTP/WebSocket server support on top of ASP.NET Core, plus authorization rule support
GraphQL.Server.Ui.Altair Provides Altair UI middleware
GraphQL.Server.Ui.Playground :warning: Provides Playground UI middleware (deprecated)
GraphQL.Server.Ui.GraphiQL Provides GraphiQL UI middleware
GraphQL.Server.Ui.Voyager 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.

: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

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

  • v7 to v8 migration notes
  • v6 to v7 migration notes

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

xml

  
    net6.0
    enable
    enable
  

  
    
  

Program.cs file

…

Schema

csharp
public class Query
{
    public static string Hero() => "Luke Skywalker";
}

Sample request url

http://localhost:5000/graphql?query={hero}

Sample response

json
{"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:

csharp
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:

csharp
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:

csharp
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

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

Using ExecutionResultHttpResult

…

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

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 Grap

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

C#aspnetcoregraphqlserver

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类后端框架
定价开源

> 相关工具

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架