(精华)2020年9月20日 ASP.NET Core WebAPI数据协议GraphQL的使用
发布日期:2021-06-29 15:12:25
浏览次数:2
分类:技术文章
本文共 8255 字,大约阅读时间需要 27 分钟。
首先要使用GraphQL安装三个包
GraphQLGraphQL.Server.Transports.AspNetCoreGraphQL.Server.Ui.Playground
定义基础类
public class Account{ public Guid Id { get; set; } public TypeOfAccount Type { get; set; } public string Description { get; set; } public Guid PersonId { get; set; } public Person Person { get; set; }}public enum TypeOfAccount{ Invalid, Free, Junior, Intermediate}
public class Person{ public Guid Id { get; set; } public string Name { get; set; } public string Address { get; set; } public ICollectionAccounts { get; set; }}
上下文
public class SampleContext{ public ListPersons { get; set; } public List Accounts { get; set; } public SampleContext() { var ids = new[] { Guid.NewGuid(), Guid.NewGuid() }; Accounts = new List { new Account { Id = Guid.NewGuid(), Type = TypeOfAccount.Junior, Description = "初级会员", PersonId = ids[0] }, new Account { Id = Guid.NewGuid(), Type = TypeOfAccount.Intermediate, Description = "中级会员", PersonId = ids[1] }, new Account { Id = Guid.NewGuid(), Type = TypeOfAccount.Free, Description = "免费会员", PersonId = ids[1] } }; Persons = new List { new Person { Id = ids[0], Name = "张三", Address = "北京" }, new Person { Id = ids[1], Name = "李四", Address = "上海" } }; }}
仓储
public interface IAccountRepository{ IEnumerableGetAllAccountsPerson(Guid personId);}public interface IPersonRepository{ IEnumerable GetAll(); Person GetById(Guid id);}
public class AccountRepository : IAccountRepository{ private readonly SampleContext _context; public AccountRepository(SampleContext context) { _context = context; } public IEnumerableGetAllAccountsPerson(Guid personId) { return _context.Accounts.Where(a => a.PersonId == personId); }}public class PersonRepository : IPersonRepository{ private readonly SampleContext _context; public PersonRepository(SampleContext context) { _context = context; } public IEnumerable GetAll() { return _context.Persons; } public Person GetById(Guid id) { return _context.Persons.SingleOrDefault(p => p.Id == id); }}
GraphQL相关类
public class AccountTypeEnumType : EnumerationGraphType{ public AccountTypeEnumType() { Name = "Type"; }}
public class AccountType : ObjectGraphType{ public AccountType() { Field(x => x.Id, type: typeof(IdGraphType)); Field(x => x.Description); Field(x => x.PersonId, type: typeof(IdGraphType)); Field ("Type", "Account类型对象的枚举"); }}
public class PersonType : ObjectGraphType{ public PersonType(IAccountRepository repository) { Field(x => x.Id, type: typeof(IdGraphType)); Field(x => x.Name); Field(x => x.Address); Field >( name: "accounts", resolve: context => repository.GetAllAccountsPerson(context.Source.Id)); }}
public class AppSchema: Schema{ public AppSchema(IDependencyResolver resolver) :base(resolver) { Query = resolver.Resolve(); }}
public class AppQuery: ObjectGraphType{ public AppQuery(IPersonRepository repository) { Field>( "persons", resolve: context => repository.GetAll() ); Field ( "person", arguments: new QueryArguments(new QueryArgument > { Name = "personId" }), resolve: context => { var personId = context.GetArgument ("personId"); if (Guid.TryParse(personId, out var id)) return repository.GetById(id); context.Errors.Add(new ExecutionError("错误的GUID格式")); return null; } ); }}
在asp.net core中使用
public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddSingleton(); services.AddScoped (); services.AddScoped (); services.AddScoped (s => new FuncDependencyResolver(s.GetRequiredService)); services.AddScoped (); services.AddGraphQL(o => { o.ExposeExceptions = false; }) .AddGraphTypes(ServiceLifetime.Scoped); services.Configure (options => { options.AllowSynchronousIO = true; }); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseAuthorization(); app.UseGraphQL (); app.UseGraphQLPlayground(options: new GraphQLPlaygroundOptions()); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } }
用localhost:5000/ui/playgroud来查看服务页面
客户端的使用如下:
public class PersonConsumer{ private readonly IGraphQLClient _client; public PersonConsumer(IGraphQLClient client) { _client = client; } public async Task
> GetAll() { var query = new GraphQLRequest { Query = @" query personsQuery{ persons { id, name, address, accounts { id, type, description } } }" }; var response = await _client.SendQueryAsync (query); return response.Data.Persons; } public async Task Get(string id) { var query = new GraphQLRequest { Query = @" query personQuery($personID: ID!) { person(personId: $personID) { id, name, address, accounts { id, type, description } } }", Variables = new { personID = id } }; var response = await _client.SendQueryAsync (query); return response.Data.Person; }}
[Route("api/[controller]")][ApiController]public class PersonController : ControllerBase{ private readonly PersonConsumer _personConsumer; public PersonController(PersonConsumer personConsumer) { _personConsumer = personConsumer; } public async TaskGet() { var persons = await _personConsumer.GetAll(); return Ok(persons); } [HttpGet("{id}")] public async Task Get(string id) { var person = await _personConsumer.Get(id); return Ok(person); }}
public class Startup{ public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddScoped(s => new GraphQLHttpClient(Configuration["GraphQLUri"], new NewtonsoftJsonSerializer())); services.AddScoped (); services.AddControllers(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }}
转载地址:https://codeboy.blog.csdn.net/article/details/108524554 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
逛到本站,mark一下
[***.202.152.39]2024年04月13日 01时25分15秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
操作系统期末大题复习
2019-04-29
hive:分区表,hbase外表
2019-04-29
想要成为运维,想要成为后期的架构师?这些知识是必备的!
2019-04-29
linux 是如何 快速一键安装禅道的呐?
2019-04-29
运维面试基础试题(四)
2019-04-29
一键安装Openstack单节点 必能成功
2019-04-29
面试紧张怎么办
2019-04-29
关系型数据库 ,nosql数据库简介
2019-04-29
Centos 7搭建NTP时间同步服务器
2019-04-29
centos7 基于rsync+inotify 实现定时备份
2019-04-29
指定IP进行 文件的分发
2019-04-29
基于http搭建本地yum仓库
2019-04-29
常规邮件基础
2019-04-29
邮件基础之 -- SMTP协议
2019-04-29
网络基础
2019-04-29
Java设计模式--责任链模式
2019-04-29
OpenCV的cvLoadImage函数
2019-04-29
OpenCV中与matlab中相对应的函数
2019-04-29
C/C++中二维数组作函数形参时,调用函数时,可传递的实参类型的小结
2019-04-29
cvGetSubRect与cvMul用法
2019-04-29