溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

C#中間件如何與GraphQL Playground集成

發(fā)布時(shí)間:2024-09-04 11:37:39 來(lái)源:億速云 閱讀:80 作者:小樊 欄目:編程語(yǔ)言

要在C#中使用GraphQL Playground,您需要首先設(shè)置一個(gè)ASP.NET Core項(xiàng)目,并安裝必要的NuGet包

  1. 創(chuàng)建一個(gè)新的ASP.NET Core Web應(yīng)用程序項(xiàng)目。

  2. 通過(guò)NuGet添加以下包:

    • GraphQL(最新穩(wěn)定版)
    • GraphQL.Server.Ui.Playground(最新穩(wěn)定版)
  3. 在項(xiàng)目的Startup.cs文件中,配置GraphQL和GraphQL Playground。這是一個(gè)示例配置:

using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using GraphQL;
using GraphQL.Types;

namespace GraphQLDemo
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton<IDocumentExecuter, DocumentExecuter>();
            services.AddSingleton<ISchema, MySchema>(); // 創(chuàng)建并注冊(cè)您自己的GraphQL Schema
            services.AddGraphQL()
                .AddSystemTextJson();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseDeveloperExceptionPage();

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGraphQL();
            });

            app.UseGraphQLPlayground(new GraphQL.Server.Ui.Playground.GraphQLPlaygroundOptions
            {
                Path = "/ui/playground"
            });
        }
    }
}
  1. 創(chuàng)建一個(gè)GraphQL Schema類(lèi),例如MySchema.cs
using GraphQL.Types;

namespace GraphQLDemo
{
    public class MySchema : Schema
    {
        public MySchema()
        {
            Query = new MyQuery();
        }
    }

    public class MyQuery : ObjectGraphType
    {
        public MyQuery()
        {
            Field<StringGraphType>("hello", resolve: context => "Hello, world!");
        }
    }
}
  1. 運(yùn)行項(xiàng)目并訪問(wèn)GraphQL Playground。URL應(yīng)為http://localhost:<port>/ui/playground,其中<port>是您的應(yīng)用程序正在運(yùn)行的端口號(hào)。

現(xiàn)在,您已經(jīng)將GraphQL Playground集成到了C# ASP.NET Core項(xiàng)目中。您可以使用Playground查詢(xún)您的GraphQL API。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI