MST
星途 面试题库

面试题:C#中GraphQL查询语言的基本类型使用

在C#项目中使用GraphQL时,假设要定义一个表示用户信息的GraphQL类型,包含姓名(字符串)、年龄(整数)和邮箱(字符串),请用代码示例展示如何在C#中定义对应的GraphQL类型,并简述如何使用它来构建简单的查询。
12.3万 热度难度
编程语言C#

知识考点

AI 面试

面试题答案

一键面试
  1. 定义GraphQL类型
    • 首先,确保安装了GraphQL.Server.Transports.AspNetCore等相关NuGet包。
    • 以下是定义用户信息GraphQL类型的代码示例:
using GraphQL.Types;

public class UserType : ObjectGraphType
{
    public UserType()
    {
        Name = "User";
        Field<StringGraphType>("name", description: "用户姓名");
        Field<IntGraphType>("age", description: "用户年龄");
        Field<StringGraphType>("email", description: "用户邮箱");
    }
}
  1. 构建简单查询
    • 定义一个查询类型,在其中使用刚刚定义的UserType
using GraphQL.Types;

public class UserQuery : ObjectGraphType
{
    public UserQuery()
    {
        Field<UserType>("user", resolve: context =>
        {
            // 这里可以从数据库或其他数据源获取用户数据,示例返回一个硬编码的用户对象
            return new { name = "张三", age = 25, email = "zhangsan@example.com" };
        });
    }
}
  • 然后在Startup.cs中配置GraphQL服务:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using GraphQL.Server;
using GraphQL.Server.Ui.Playground;
using GraphQL.Types;

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<ISchema, GraphQLSchema>();
        services.AddSingleton<UserType>();
        services.AddSingleton<UserQuery>();
        services.AddGraphQL();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseGraphQL<ISchema>();
        app.UseGraphQLPlayground(new GraphQLPlaygroundOptions());
    }
}
  • 最后,在浏览器中访问GraphQL Playground(http://localhost:5000/graphql,端口根据实际情况调整),可以执行如下查询:
{
  user {
    name
    age
    email
  }
}

这个查询会返回定义的用户信息。

请注意,以上代码中的硬编码用户数据仅为示例,实际应用中应从数据库或其他数据源获取数据。同时,GraphQL的配置和使用可能因项目需求和框架版本有所不同。