当前位置: 首页 > 技术突破

如何使用ASP.NET Core创建GraphQl API

时间:2024-02-27 22:25:24 技术突破

  创建ASP.NET核心Web API项目:

  使用Dotnet CLI使用文章中提供的命令来创建一个新项目:

  sh

  dotnet新webapi -n graphqldemo

  2.导航到项目目录:

  sh

  CD GraphQldemo

  3.添加必要的GraphQl库:

  安装Hotchocaly和Hotchocaly Playground套餐:

  sh

  dotnet添加软件包hotchocaly.aspnetcore

  dotnet添加软件包hotchocaly.aspnetcore.playground

  4.创建一个模型:

  在“模型”文件夹中(如果不存在,则可能需要创建它),例如:以下数据模型:

  CSHARP

  公共课程

  {

  public int id {get;放;}

  公共字符串标题{get;放;}

  公共字符串作者{get;放;}

  }

  5.创建GraphQL架构:

  定义GraphQl API的类型和根查询:

  CSHARP

  公共类查询

  {

  私人静态列表_Books =新列表

  {

  新书{id = 1,title =“ 1984”,作者=“乔治·奥威尔”},

  新书{id = 2,title =“杀死模仿鸟”,作者=“ Harper Lee”},

  新书{id = 3,title =“大盖茨比”,作者=“ F. Scott Fitzgerald”}

  };

  //查询所有书籍

  公共列表getBooks()=> _Books;

  //查询以通过ID获取一本书

  公共图书getBook(int id)=> _Books.firstordEfault(book => book.id == id);

  }

  6.配置服务:

  在“启动.cs”文件中,在“配置”方法中注册GraphQl服务:

  CSHARP

  公共Void Configureservices(IservCollection Services)

  {

  services.addgraphqlserver()

  .addqueryType();

  //如果需要,请添加其他服务(例如控制器,CORS等)

  services.addcontrollers();

  }

  7.添加中间件:

  在“ startup.cs”文件中,将GraphQL中间件添加到`configure'方法:

  CSHARP

  公共void配置(iapplicationbuilder应用程序,iwebhostenvironment env)

  {

  //其他配置(例如app.usehttpsredirection(),app.usestaticfiles()此处...

  app.userouting();

  App.UseEndPoints(endpoints =>

  {

  endpoints.mapgraphql();

  });

  app.useplayground();//仅出于开发目的

  }

  8.运行应用程序:

  使用dotnet cli运行应用程序:

  sh

  dotnet运行

  现在,您应该拥有带有ASP.NET Core的工作GraphQL API,您可以使用Postman或任何其他GraphQL客户端进行测试。操场软件包提供了一个不错的Web界面来手动测试您的GraphQl API,可以通过导航到API的URL(通常是在本地运行)来达到的。-04 07:44:26“},{“ id”:1963,“ body”:“如何配置.netcore”,“ sender”:“ user”,“ create_at”:“ 2023-12-04 07:43:32“},{“ id”:1962,“身体”:“如果您对使用ASP.NET核心创建GraphQl API有任何疑问或需要帮助,请随时提出!我在这里为您提供帮助。”,“发送者”:“ GPT”,“ create_at”:“ 2023-12-04 07:43:13”},{“ id”:1961,“ Body”:“ \\”,“ sender”:“用户”,“ create_at”:“ 2023-12-04 07:43:11”}]}}}}}“ data-react-cache-id =”媒体/chat_posts/chat_posts/chatbobs-0 class = class =“ wrapper-chat_box” id =“ chats-box”>