(精华)2020年9月20日 ASP.NET Core WebAPI数据协议GraphQL的使用
发布日期:2021-06-29 15:12:25
浏览次数:3
分类:技术文章
本文共 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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
初次前来,多多关照!
[***.217.46.12]2024年04月13日 21时10分32秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
猿来绘Java-38-生产者消费者模型
2019-04-29
猿来绘Java-39-JDK8的新日期时间类
2019-04-29
猿来绘Java-40-比较器(Comparable 接口与 CompareTo方法)
2019-04-29
猿来绘Java-41-源码分析String对象的数组的排序(JDK1.8)
2019-04-29
猿来绘Java-42-枚举类的使用
2019-04-29
猿来绘Java-43-初步认识注解
2019-04-29
猿来绘Java-44-自定义注解和元注解
2019-04-29
猿来绘Java-45-JDK8新特性可重复注解和类型注解
2019-04-29
猿来绘Java-46-Collection接口及其方法
2019-04-29
猿来绘Java-47- foreatch 增强for循环
2019-04-29
2021/4/27课堂总结和作业
2019-04-29
2021.4.28课堂总结和作业
2019-04-29
2021.4.29课堂总结
2019-04-29
2021.4.30课堂总结和作业
2019-04-29
需要吗?2000GB+学习视频教程 面试资料免费下载
2019-04-29
MySQL对已存在数据库表添加自增ID字段
2019-04-29
idea中的一些常用快捷键
2019-04-29
js校验表单后提交表单的三种方法总结【转载】
2019-04-29
欢迎使用CSDN-markdown编辑器
2019-04-29