asp.net core 微服务网关示例 ocelot gateway Demo
ocelot asp.net core 微服务 gateway介绍
https://ocelot.readthedocs.io/en/latest/introduction/gettingstarted.html
1. 新建asp.net core webapi空项目 AProject, nuget引用ocelot插件
2. 新建asp.net core webapi示例项目BProject,并实现todoitemscontroller get方法,http://localhost:22/api/todoitems
3. 在AProject项目,新建ocelot.json
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | { "Routes" : [ { //下游请求 "DownstreamPathTemplate" : "/api/todoitems/" , "DownstreamScheme" : "http" , "DownstreamHostAndPorts" : [ { "Host" : "localhost" , "Port" : 22 } ], //上游请求 "UpstreamPathTemplate" : "/todoitems/" , "UpstreamHttpMethod" : [ "Get" ] } ],<br> //Gateway 的地址 "GlobalConfiguration" : { "BaseUrl" : "http://localhost:5211" } } |
在AProject项目,Program.cs 文件里 写以下代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | using Ocelot.DependencyInjection; using Ocelot.Middleware; new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .ConfigureAppConfiguration((hostingContext, config) => { config .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath) .AddJsonFile( "appsettings.json" , true , true ) .AddJsonFile($ "appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json" , true , true ) .AddJsonFile( "ocelot.json" ) .AddEnvironmentVariables(); }) .ConfigureServices(s => { s.AddOcelot(); }) .ConfigureLogging((hostingContext, logging) => { //add your logging }) .UseIISIntegration() .Configure(app => { app.UseOcelot().Wait(); }) .Build() .Run(); |
启动AProject、BProject项目, 此时访问:
http://localhost:5211/todoitems/ 会跳到http://localhost:22/api/todoitems/
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决