{"id":19094848,"url":"https://github.com/sflaqiu/graphqldemo","last_synced_at":"2025-08-13T17:05:31.752Z","repository":{"id":74296182,"uuid":"130346923","full_name":"SFLAQiu/GraphQLDemo","owner":"SFLAQiu","description":":flags: 基于GraphQL的ASP.NET WebAPI Demo","archived":false,"fork":false,"pushed_at":"2019-03-04T00:55:31.000Z","size":163,"stargazers_count":5,"open_issues_count":0,"forks_count":4,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-07-26T01:38:49.024Z","etag":null,"topics":["asp-net-mvc","donet","graphql","graphql-dotnet","graphql-server"],"latest_commit_sha":null,"homepage":"https://blog.thankbabe.com/2018/04/20/graphql/","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/SFLAQiu.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-04-20T10:23:11.000Z","updated_at":"2019-08-05T03:33:11.000Z","dependencies_parsed_at":null,"dependency_job_id":"2b9bcd0d-961e-41b6-8819-23b1b01e060d","html_url":"https://github.com/SFLAQiu/GraphQLDemo","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/SFLAQiu/GraphQLDemo","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SFLAQiu%2FGraphQLDemo","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SFLAQiu%2FGraphQLDemo/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SFLAQiu%2FGraphQLDemo/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SFLAQiu%2FGraphQLDemo/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/SFLAQiu","download_url":"https://codeload.github.com/SFLAQiu/GraphQLDemo/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SFLAQiu%2FGraphQLDemo/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":270278338,"owners_count":24557172,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-08-13T02:00:09.904Z","response_time":66,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["asp-net-mvc","donet","graphql","graphql-dotnet","graphql-server"],"created_at":"2024-11-09T03:31:47.328Z","updated_at":"2025-08-13T17:05:31.715Z","avatar_url":"https://github.com/SFLAQiu.png","language":"C#","funding_links":[],"categories":[],"sub_categories":[],"readme":"\n![graphql](http://blog.thankbabe.com/imgs/graphql.png?v=2)\n\n### GraphQL是什么？\nGraphQL 既是一种用于API的查询语言也是一个满足你数据查询的运行时（来自：[官方解释](http://graphql.cn/learn/)）\n\n理解起来就是，GraphQL有自己查询语法，发起的API请求中通过传递查询语句来告诉服务端需要哪些操作和具体数据字段，GraphQL定义了实现规范，各种的语言分别实现了GraphQL功能框架，通过框架可以对查询语法进行解释执行，然后返回数据输出给客户端\n\n![graphql](http://blog.thankbabe.com/imgs/graphql-server.png?v=2)\n\n---\n\n\n### GraphQL的优势\n\n\u003e 以下所有查询和输出都是来自我的DEMO，DEMO的实现和源码Github地址下面会提到\n\n**语法特性满足各种需求**\n\n* 支持多操作：query-\u003e查询，mutation-\u003e修改，规范是写在查询语句前，默认不写就是query\n* 支持参数，实现各种功能，比如：查询数据，排序，分页，... ...等\n* 语法其他特性，别名，片段，定义变量，指令，... ...等\n\n\n```\n# 查询语句-有参数\nquery{\n  student(id:86){\n    id\n    name\n    sclass{\n      id\n      num\n      level\n      heads\n    }\n  }\n}\n```\n\n```\n# 输出\n{\n  \"data\": {\n    \"student\": {\n      \"id\": 86,\n      \"name\": \"Emma\",\n      \"sclass\": {\n        \"id\": 9,\n        \"num\": 8,\n        \"level\": 3,\n        \"heads\": 68\n      }\n    }\n  }\n}\n```\n\n```\n# 修改\nmutation {\n  update(id: 86, name: \"66666\") {\n    rt\n    msg\n  }\n}\n\n```\n\n```\n# 输出\n{\n  \"data\": {\n    \"update\": {\n      \"rt\": 1,\n      \"msg\": \"bingo\"\n    }\n  }\n}\n```\n---\n\n**查询友好性，查询和输出关联**\n\n看查询语句是不是感觉有点儿JSON的味道？查询语法类JSON格式，前后端都可以很容易上手，查询语句和输出数据有紧密的关联性，通过分析查询语句就知道输出的数据内容字段有哪些\n\n---\n\n**灵活性，请求你所要的数据，不多不少**\n\n可以自定义查询语句来获取需要使用的字段，避免无用字段的输出，减少不必要数据块/数据字段查询逻辑\n\n\n\u003e 多字段\n\n```\n# 查询语句\nquery{\n  students{\n    id\n    name\n    classid\n    sclass{\n      id\n      num\n      level\n      heads\n    }\n  }\n}\n```\n\n```\n# 输出\n{\n  \"data\": {\n    \"students\": [\n       {\n        \"id\": 19,\n        \"name\": \"Savannah\",\n        \"classid\":22,\n        \"sclass\": {\n          \"id\": 22,\n          \"num\": 6,\n          \"level\": 4,\n          \"heads\": 57\n        }\n      },\n      {\n        \"id\": 34,\n        \"name\": \"Ariana\",\n        \"classid\":33,\n        \"sclass\": {\n          \"id\": 33,\n          \"num\": 3,\n          \"level\": 4,\n          \"heads\": 57\n        }\n      }\n    ]\n  }\n}\n```\n\n\u003e 去掉了不使用的字段输出，少了字段sclass，就可以不进行sclass数据查询\n\n```\n# 查询语句\nquery{\n  students{\n    id\n    name\n  }\n}\n```\n\n```\n# 输出\n{\n  \"data\": {\n    \"students\": [\n      {\n        \"id\": 19,\n        \"name\": \"Savannah\"\n      },\n      {\n        \"id\": 34,\n        \"name\": \"Ariana\"\n      }\n    ]\n  }\n}\n```\n\n---\n\n\n**API演进，无需划分版本**\n\nAPI版本迭代无需要进行版本号区分，添加字段不影响现有查询，请求发起者可以自己定义想要的查询信息\n\n```\n# Say No\nhttp://api.xxx.com/student/v1/\nhttp://api.xxx.com/student/v2/\n# ... \n```\n\n---\n \n**自检性，可查询输出所有定义**\n\n这个是GraphQL一个很Nice的特性，就是GraphQL服务API可以通过语句查询出它所支持的类型，开发可以不需要花时间写API文档，GraphQL直接帮助开发者快速了解API。\n\n\n```\n# 查询语句\n{\n  __type(name: \"MStudentType\") {\n    kind\n    name\n    fields {\n      name\n      description\n      type {\n        name\n      }\n    }\n  }\n}\n\n\n```\n\n```\n# 输出\n{\n  \"data\": {\n    \"__type\": {\n      \"kind\": \"OBJECT\",\n      \"name\": \"MStudentType\",\n      \"fields\": [\n        {\n          \"name\": \"id\",\n          \"description\": \"学号\",\n          \"type\": {\n            \"name\": null\n          }\n        },\n        {\n          \"name\": \"name\",\n          \"description\": \"学生名\",\n          \"type\": {\n            \"name\": null\n          }\n        },\n        {\n          \"name\": \"age\",\n          \"description\": \"年龄\",\n          \"type\": {\n            \"name\": null\n          }\n        },\n        {\n          \"name\": \"birthdate\",\n          \"description\": \"生日\",\n          \"type\": {\n            \"name\": null\n          }\n        },\n        {\n          \"name\": \"sclass\",\n          \"description\": \"班级信息\",\n          \"type\": {\n            \"name\": \"MClassType\"\n          }\n        }\n      ]\n    }\n  }\n}\n\n```\n\n基于自检性，GraphQL开源了辅助工具GraphiQL，方便GraphQL接口调试和自动生成接口文档     \n* GraphQL辅助工具：GraphiQL，可以调试查询语句，并对接口定义的schema进行文档可视化展示\n  * 查询语句进行感知\n  * 错误提示\n  * 语句格式化\n  * 执行查询\n  * 查看接口定义的schema文档信息\n    \n\u003e graphql-dotnet开源项目里的GraphiQL要接入自己开发GraphQL接口，还需要进行简单的修改调整，后面会说到\n\n---\n\n\n### .NET下的入门教程\n\n* 构建ASP.NET MVC5 WebAPI 项目\n* NutGet引入程序包\n    * [GraphQL](https://github.com/graphql-dotnet/graphql-dotnet/) \n    * [GenFu](https://github.com/MisterJames/GenFu)，用于初始化测试数据\n* 基于GraphQL简单实现一个学生查询API\n    * 支持查询学生信息列表\n    * 支持查询学生的班级信息\n    * 支持查询学号对应的学生信息\n    * 支持修改学生名字\n\n定义【数据类】MStudent.cs(学生类)，MClass.cs(班级类)，MResult.cs(执行结果类)\n\n```csharp\n\npublic class MStudent {\n    /// \u003csummary\u003e\n    /// 学号\n    /// \u003c/summary\u003e\n    public int Id { get; set; }\n    /// \u003csummary\u003e\n    /// 名字\n    /// \u003c/summary\u003e\n    public string Name { get; set; }\n    /// \u003csummary\u003e\n    /// 年龄\n    /// \u003c/summary\u003e\n    public int Age { get; set; }\n    /// \u003csummary\u003e\n    /// 所在班级编号\n    /// \u003c/summary\u003e\n    public int ClassId { get; set; }\n    /// \u003csummary\u003e\n    /// 生日\n    /// \u003c/summary\u003e\n    public DateTime Birthdate { get; set; }\n    /// \u003csummary\u003e\n    /// 班级\n    /// \u003c/summary\u003e\n    public MClass SClass { get; set; }\n}\n\npublic class MClass {\n    public int Id { get; set; }\n    /// \u003csummary\u003e\n    /// 年级\n    /// \u003c/summary\u003e\n    public int Level { get; set; }\n    /// \u003csummary\u003e\n    /// 第几班\n    /// \u003c/summary\u003e\n    public int Num { get; set; }\n    /// \u003csummary\u003e\n    /// 总人数\n    /// \u003c/summary\u003e\n    public int Heads { get; set; }\n}\n\npublic class MResult {\n    /// \u003csummary\u003e\n    /// 输出结果,0=失败，1=成功\n    /// \u003c/summary\u003e\n    public int rt { get; set; }\n    /// \u003csummary\u003e\n    /// 说明信息\n    /// \u003c/summary\u003e\n    public string msg { get; set; }\n}\n\n```\n\n定义GraphType类 MStudentType,MClassType,MResultType 继承ObjectGraphType\u003cTSourceType\u003e ，TSourceType泛型对应到【数据类】     \n构造函数里通过Field去添加可以被查询的数据字段，包括：描述以及字段内容获取的处理方法，等    \n\n```csharp\n\npublic class MStudentType : ObjectGraphType\u003cMStudent\u003e {\n    private static BStudent _bll { get; set; }\n    public MStudentType() {\n        if (_bll == null) _bll = new BStudent();\n        Field(d =\u003e d.Id).Description(\"学号\");\n        Field(d =\u003e d.Name).Description(\"学生名\");\n        Field(d =\u003e d.Age).Description(\"年龄\");\n        Field(d =\u003e d.Birthdate).Description(\"生日\");\n        Field\u003cMClassType\u003e(\"sclass\", resolve: d =\u003e {\n            //缓存中已经存在就直接返回\n            if (d.Source.SClass != null) return d.Source.SClass;\n            //从DB/缓存中获取数据\n            var classId = d.Source?.ClassId ?? 0;\n            if (classId \u003e 0) d.Source.SClass = _bll.GetClass(d.Source.ClassId);\n            return d.Source.SClass;\n        },description:\"班级信息\");\n    }\n}\n\npublic class MClassType : ObjectGraphType\u003cMClass\u003e {\n    public MClassType() {\n        Field(d =\u003e d.Level).Description(\"年级\");\n        Field(d =\u003e d.Heads).Description(\"人数\");\n        Field(d =\u003e d.Id).Description(\"编号\");\n        Field(d =\u003e d.Num).Description(\"班级\");\n    }\n}\n\npublic class MResultType : ObjectGraphType\u003cMResult\u003e {\n    public MResultType() {\n        Field(d =\u003e d.rt);\n        Field(d =\u003e d.msg);\n    }\n}\n\n```\n\n\n定义Schema的操作类(query/mutation)，继承 ObjectGraphType，有：StudentQuery，StudentMutation\n\n\n```csharp\n\npublic class StudentQuery : ObjectGraphType {\n        public StudentQuery(BStudent bll) {\n            //查询-有参数id\n            Field\u003cMStudentType\u003e(\"student\", arguments: new QueryArguments(new QueryArgument\u003cIntGraphType\u003e() {\n                Name = \"id\"\n            }), resolve: d =\u003e {\n                var id = d.Arguments[\"id\"].GetInt(0, false);\n                return bll.GetModel(id); ;\n            });\n            //查询-列表\n            Field\u003cListGraphType\u003cMStudentType\u003e\u003e(\"students\", resolve: d =\u003e {\n                return bll.GetStudents();\n            });\n        }\n    }\n}\n\npublic class StudentMutation : ObjectGraphType {\n    public StudentMutation(BStudent bll) {\n        Field\u003cMResultType\u003e(\"update\", arguments: new QueryArguments(\n            new QueryArgument\u003cIntGraphType\u003e {\n                Name = \"id\"\n            },\n            new QueryArgument\u003cStringGraphType\u003e {\n                Name = \"name\"\n            }\n        ), resolve: (d) =\u003e {\n            var id = d.Arguments[\"id\"].GetInt(0, false);\n            var name = d.Arguments[\"name\"].GetString(\"\");\n            if (id \u003c= 0) return new MResult {\n                rt = 0,\n                msg = \"非法学号\"\n            };\n            if (name.IsNullOrWhiteSpace()) return new MResult {\n                rt = 0,\n                msg = \"非法名字\"\n            };\n            var isSc = bll.UpdateName(id, name);\n            if (!isSc) return new MResult {\n                rt = 0,\n                msg = \"更新失败\"\n            };\n            return new MResult {\n                rt = 1,\n                msg = \"bingo\"\n            };\n        });\n    }\n}\n\n```\n\n在控制器里添加接口，构造Schema对象，根据查询条件解析执行返回结果输出    \nQuery = StudentQuery，Mutation = StudentMutation    \n\n```csharp\n/// \u003csummary\u003e\n/// graphql demo 接口\n/// \u003c/summary\u003e\n/// \u003creturns\u003e\u003c/returns\u003e\n[HttpPost]\n[Route(\"query\")]\npublic object Test_Query() {\n    var r = HttpContext.Current.Request;\n    var query = r.GetF(\"query\");\n    var bll = new BStudent();\n    var schema = new Schema { Query = new StudentQuery(bll), Mutation = new StudentMutation(bll) };\n    var result = new DocumentExecuter()\n        .ExecuteAsync(options =\u003e {\n            options.Schema = schema;\n            options.Query = query;\n        }).GetAwaiter();\n    var json = new DocumentWriter(indent: true).Write(result);\n    return result.GetResult();\n}\n\n```\n---\n\n**GraphiQL工具的接入**\n\n* Git Clone [graphql-dotnet](https://github.com/graphql-dotnet/graphql-dotnet)\n* 安装NodeJS环境\n* 命令工具CMD打开graphql-dotnet/src/GraphQL.GraphiQL/ 执行下面命令\n    * npm install -g yarn\n    * yarn install\n    * yarn start\n* 运行graphql-dotnet/src/GraphQL.GraphiQL 就可以启动：http://localhost:47080/\n* 根据自己的情况调整：graphql-dotnet/src/GraphQL.GraphiQL/app/app.js 脚本，如下面贴出的代码\n    * url=graphql接口地址\n    * 如果需要投入生产使用，可以把接口地址进行url传入，或者支持输入框输入地址，不固定接口地址\n* 每次调整完需要重新执行  yarn start，前端会使用webpack进行打包操作，执行完成后刷新页面即可\n\n\n```javascript\n\n//调整如下\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport GraphiQL from 'graphiql';\nimport axios from 'axios';\nimport 'graphiql/graphiql.css';\nimport './app.css';\n\nfunction graphQLFetcher(graphQLParams) {\n    console.log(graphQLParams[\"query\"]);\n    return axios({\n        method: 'post',\n        url: \"http://127.0.0.1:5656/query\",//window.location.origin + '/api/graphql',\n        data: \"query=\" + graphQLParams[\"query\"],\n        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }\n    }).then(resp =\u003e resp.data);\n}\nReactDOM.render(\u003cGraphiQL fetcher={graphQLFetcher} /\u003e, document.getElementById('app'));\n\n```  \n\n![graphql](http://blog.thankbabe.com/imgs/graphiql.jpg?v=1)\n\n### 总结\n\n* 对于应用我觉得可以尝试使用到新项目需求中，或者现有合适应用场景进行重构，等服务运行稳定，并且开发上手后即可进行大范围的使用\n* 对于RestFul和GraphQL的比较，我觉得没有最好的协议，只有最合适的场景\n\n---\n### 资源\n* Demo源码：\n  * Demo代码到我的Gtihub项目（[GraphQLDemo](https://github.com/SFLAQiu/GraphQLDemo)）\n* 学习资料\n  * [知乎-什么是GraphQL](https://www.zhihu.com/question/264629587)\n  * [GraphQL语法入门](http://graphql.cn/learn/)\n  * [GraphQL中文官网](http://graphql.cn)\n  * [How To GraphQL](http://howtographql.cn/)\n  * [GraphQL 搭配 Koa 最佳入门实践](https://juejin.im/post/5a49e5ccf265da430d585cfd)\n \n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsflaqiu%2Fgraphqldemo","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsflaqiu%2Fgraphqldemo","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsflaqiu%2Fgraphqldemo/lists"}