Net6.0 集成 支持 Nacos 的 Ocelot 网关

1-创建 Ocelot 网关 webapi

 2-添加引用

https://www.cnblogs.com/wucy/p/13353824.html

1
2
3
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

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
30
31
32
33
34
{
  "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 配置

 

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
30
31
32
33
34
35
36
37
38
{
    "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

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
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();

  

 

 启动服务就可以了,然后根据配置路由就可以访问其他的服务了

 

posted @   细品人生  阅读(452)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性
· 2025年我用 Compose 写了一个 Todo App
历史上的今天:
2016-08-15 一个简单的NetCore项目:2 - 登录
点击右上角即可分享
微信分享提示