面试题答案
一键面试- 定义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: "用户邮箱");
}
}
- 构建简单查询:
- 定义一个查询类型,在其中使用刚刚定义的
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的配置和使用可能因项目需求和框架版本有所不同。