.net core接入nacos注册服务并使用配置中心

1、安装依赖

Nuget包:nacos-sdk-csharp.Extensions.Configuration和nacos-sdk-csharp.AspNetCore

2、在appsettings.json中配置

复制代码
"nacos": {
    "ServerAddresses": [
      "http://localhost:8848/"
    ],
    "DefaultTimeOut": 15000,
    "Namespace": "xxxxx",//命名空间
    "ListenInterval": 5000,
    "ServiceName": "testService",//服务名称
    "GroupName": "DEFAULT_GROUP",//组明
    "ClusterName": "DEFAULT",
    "Ip": "",
    "PreferredNetworks": "",
    "Port": 0,
    "Weight": 1,
    "RegisterEnabled": true,
    "InstanceEnabled": true,
    "Ephemeral": true,
    "Secure": false,
    "AccessKey": "",
    "SecretKey": "",
    "UserName": "nacos",//用户名
    "Password": "nacos",//密码
    "ConfigUseRpc": false,
    "NamingUseRpc": false,
    "NamingLoadCacheAtStart": "",
    "LBStrategy": "WeightRandom",
    //下方是注册中心专用,如果不需要配置中心则可不配置
    "Listeners": [
      {
        "Group": "DEFAULT_GROUP",
        "DataId": "test-dev.json",
        "Optional": false
      }
    ]
  }

3、在Program.cs中注入服务

复制代码
builder.Services.AddNacosAspNet(builder.Configuration, section:"nacos");
builder.Configuration.AddNacosV2Configuration(builder.Configuration.GetSection("nacos"));//如果不使用服务注册中心可不写他

4、注.net 中需要添加如下开放IP

复制代码
builder.WebHost.UseUrls("http://*:5065");

5、启动可看到

6、如果配置了nacos的配置文件的话

测试用例

复制代码
public class TestController : ControllerBase
{
  private readonly IConfiguration _configuration;

    public TestController(IConfiguration configuration)
    {
        this._configuration = configuration;
    }
    
    [HttpGet("getConfig")]
    public string getConfig() => _configuration["a1"];
}
相关推荐
czhc11400756639 分钟前
2026-08-25 博客:现场排查的 8 个坑
c#
Z5998178411 小时前
c#软件开发学习笔记--WPF(控件、样式)
笔记·学习·c#
格林威1 小时前
C#高位深相机图像保存:12位16位图像保存方案,OpenCvSharp和Halcon实现
开发语言·人工智能·数码相机·计算机视觉·c#·视觉检测·工业相机
aikopen1 小时前
高可用 API 网关限流与微服务过载保护实战:从 Sentinel 动态阈值到 DB 连接池舱壁
数据库·微服务·sentinel
雪隐1 小时前
WPF + MVVM 实战系列03-MVVM 的边界之争,终于有人画了条“差不多”的线
c#
影寂ldy1 小时前
C# WinForm TCP聊天室(服务端+客户端)
windows·tcp/ip·c#
星期一研究室2 小时前
用《颜色》管理项目,混乱现场快速变清晰
微服务·产品·设计
七仔啊2 小时前
C#、.NET 、ASP.NET Core、Visual Studio全系列快速入门
c#·asp.net·.net
李高钢14 小时前
REST vs gRPC 选型对比与迁移实践:从原理到落地
c#·集成·winforms
一个帅气昵称啊16 小时前
.Net C# AI智能体开发-快速开始
开发语言·c#·.net