.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"];
}
相关推荐
Chris _data1 小时前
并发单词频率统计器 - 从零到完整实现(C# 实战)
开发语言·c#
iCxhust11 小时前
C# 命令行指令 查看二进制文件
开发语言·单片机·嵌入式硬件·c#·proteus·微机原理·8088单板机
雪豹阿伟13 小时前
15.C# —— 多接口,泛型方法,泛型效率、泛型类和泛型接口、泛型约束
c#·上位机
影寂ldy13 小时前
C# const 常量 / readonly 只读 / static readonly
java·开发语言·c#
iCxhust14 小时前
c#多串口重量采集上位机程序
开发语言·汇编·c#·微机原理·8088单板机
雪豹阿伟15 小时前
14.C# —— 虚方法,new/override,密封类,索引器,接口
c#·上位机
糖果店的幽灵15 小时前
LangChain 1.3 完全教程:从入门到精通-Part 11: Tools(工具系统)
开发语言·langchain·c#
阿里云云原生15 小时前
阿里云微服务引擎 MSE 及 API 网关 2026 年 5 月产品动态
微服务
专注VB编程开发20年19 小时前
python翻译网页HTML的难题
python·c#·html