1-创建 Ocelot 网关 webapi
2-添加引用
https://www.cnblogs.com/wucy/p/13353824.html
Install-Package nacos-sdk-csharp -Version 1.3.5 Install-Package Ocelot.Provider.Nacos -Version 1.3.5 Install-Package Ocelot.Provider.Polly -Version 1.3.5
3-配置 appsettings.json
{ "GlobalConfiguration": { "ServiceDiscoveryProvider": { "Type": "Nacos" //开启服务发现 } }, "Nacos": { "Listeners": [ //对应配置文件 { "Optional": false, "DataId": "common", //配置名称 "Group": "DEFAULT_GROUP" //组名 }, { "Optional": false, "DataId": "gateway", "Group": "DEFAULT_GROUP" } ], "DefaultTimeOut": 15, "ListenInterval": 1000, "ServiceName": "gatewayApiSrv", "Namespace": "public", //对应的是命名空间的Id "ServerAddresses": [ "http://ip地址:8848/" ], //是Nacos的服务器地址,可以添加多个 "UserName": "nacos", "Password": "1Q2w3e4r$", "RegisterEnabled": true, "InstanceEnabled": true, "LBStrategy": "WeightRoundRobin", "ConfigUseRpc": false, //false-http协议,true-grpc "NamingUseRpc": false //false-http协议,true-grpc }, "Urls": "http://*:5100" }
4- nacos 配置
{ "Routes":[ { "ServiceName":"userApiSrv", "UpstreamPathTemplate":"/api/Account/Login", "UpstreamHttpMethod": [ "Get","Post","Put", "Delete" ], "LoadBalancerOptions": { "Type": "LeastConnection" }, "UseServiceDiscovery": true, "DownstreamPathTemplate":"/api/Account/Login", "DownstreamScheme":"http", "DownstreamHostAndPorts":[ { "Host": "192.168.108.115", "Port": 5101 } ] }, { "ServiceName":"userApiSrv", "UpstreamPathTemplate":"/api/Account/Detail/{id}", "UpstreamHttpMethod": [ "Get"], "LoadBalancerOptions": { "Type": "LeastConnection" }, "UseServiceDiscovery": true, "DownstreamPathTemplate":"/api/Account/Detail/{id}", "DownstreamScheme":"http", "DownstreamHostAndPorts":[ { "Host": "192.168.108.115", "Port": 5101 } ] } ] }
网关参数配置请参考:https://www.cnblogs.com/jesse2013/p/net-core-apigateway-ocelot-docs.html
5- 配置 program.cs
using Serilog; using Microsoft.AspNetCore.Mvc; using System.Text.Encodings.Web; using System.Text.Unicode; using MicroSrv.User.HostApi.JSON; using Kinwong.Logger; using Kinwong.Swagger.NSwag; using Nacos.AspNetCore.V2; using Nacos.V2.DependencyInjection; using Ocelot.DependencyInjection; using Ocelot.Provider.Nacos; using Ocelot.Middleware; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddNacosAspNet(builder.Configuration, section: "Nacos"); builder.Services.AddOcelot().AddNacosDiscovery(section: "Nacos"); builder.Host.UseNacosConfig("Nacos", logAction: x => x.AddSerilog()); builder.Services.AddOptions(); //builder.Services.AddNacosWeb(builder.Configuration, builder.Configuration, section: "Nacos"); var _myAllowSpecificOrigins = "_myAllowSpecificOrigins"; builder.Host.UseSerilog((context, services, logger) => { logger.ReadFrom.Configuration(context.Configuration) .ReadFrom.Services(services); logger.Enrich.FromLogContext(); }); builder.Services.Configure<ApiBehaviorOptions>(options => { //禁用自定义验证 options.SuppressModelStateInvalidFilter = true; //options.InvalidModelStateResponseFactory = context => //{ // var error = context.ModelState.GetValidationSummary(); // ////自定义自己想要返回的数据结果,我这里要返回的是Json对象,通过引用Newtonsoft.Json库进行转换 // var payload = JsonConvert.SerializeObject(Result.Error(HttpStatusCode.BadRequest.ToCode(), error)); // //////自定义返回的数据类型 // //context.HttpContext.Response.ContentType = "application/json"; // //////自定义返回状态码,默认为401 我这里改成 200 // //context.HttpContext.Response.StatusCode = StatusCodes.Status200OK; // //////context.Response.StatusCode = StatusCodes.Status401Unauthorized; // //////输出Json数据结果 // //context.HttpContext.Response.WriteAsync(payload); // return new ObjectResult(error); //}; }); builder.Services.AddHttpContextAccessor(); builder.Services.AddCors(c => { //https://learn.microsoft.com/zh-cn/aspnet/core/security/cors?view=aspnetcore-6.0 var cors = builder.Configuration.GetSection("Cors").Value; if (!string.IsNullOrWhiteSpace(cors)) { c.AddPolicy(_myAllowSpecificOrigins, policy => { policy.WithOrigins(cors.Split(',')) .AllowAnyMethod() .AllowAnyHeader(); }); } else { c.AddPolicy(_myAllowSpecificOrigins, policy => { policy.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader(); }); } }); builder.Services.AddControllers() .AddJsonOptions(options => { //https://learn.microsoft.com/zh-cn/aspnet/core/web-api/advanced/formatting?view=aspnetcore-6.0 //配置 小写 格式,而不是默认的 camelCase 格式 options.JsonSerializerOptions.PropertyNamingPolicy = new LowercasePolicy(); //中文转义处理 options.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All); //忽略大小写 options.JsonSerializerOptions.PropertyNameCaseInsensitive = true; }); builder.Services.AddNSwagger(title: "Gateway系统API接口文档", description: "API接口说明文档", contact: new NSwag.OpenApiContact { Url = "", Name = "" }); var app = builder.Build(); app.UseSerilogRequestLogging(); app.UseNSwagger(); app.UseOcelot().Wait(); app.UseAuthentication(); app.UseAuthorization(); // Configure the HTTP request pipeline. app.MapControllers(); app.Run();
启动服务就可以了,然后根据配置路由就可以访问其他的服务了
标签:网关,builder,Nacos,Ocelot,Services,using,true,app From: https://www.cnblogs.com/ganqiyin/p/17632093.html