• Stars
    star
    420
  • Rank 103,194 (Top 3 %)
  • Language
    C#
  • License
    Apache License 2.0
  • Created over 4 years ago
  • Updated about 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

This nacos csharp sdk

nacos-sdk-csharp ใ€€ใ€€ใ€€ใ€€ใ€€ ใ€€ใ€€ ใ€€ใ€€ใ€€ไธญๆ–‡

csharp(dotnet core) implementation of nacos OpenAPI.

Build Release

Installation

Choose a package that you need.

dotnet add package nacos-sdk-csharp
dotnet add package nacos-sdk-csharp.AspNetCore
dotnet add package nacos-sdk-csharp.Extensions.Configuration
dotnet add package nacos-sdk-csharp.YamlParser
dotnet add package nacos-sdk-csharp.IniParser

NOTE: The packages' name has remove the suffix unofficial.

Features

  • Basic OpenApi Usages
  • Integrate ASP.NET Core Configuration System
  • Service Registration and Discovery With ASP.NET Core
  • Integrate With Aliyun MSE/ACM
  • ...

Find more information on the documents pages:

https://nacos-sdk-csharp.readthedocs.io/en/latest/

Basic Usage

Simple Configuration Usage

  1. Configure in Program.cs
// after v1.3.3, we can use UseNacosConfig to simplify
public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .UseNacosConfig(section: "NacosConfig", parser: null logAction: null)
        // .UseNacosConfig(section: "NacosConfig", parser: Nacos.YamlParser.YamlConfigurationStringParser.Instance logAction: null)
        // .UseNacosConfig(section: "NacosConfig", parser: Nacos.IniParser.IniConfigurationStringParser.Instance logAction: null)       
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

// before v1.3.3
public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((context, builder) =>
        {
            var c = builder.Build();

           // read configuration from config files
            // it will use default json parser to parse the configuration store in nacos server.
            builder.AddNacosV2Configuration(c.GetSection("NacosConfig"));
            // you also can specify ini or yaml parser as well.
            // builder.AddNacosV2Configuration(c.GetSection("NacosConfig"), Nacos.IniParser.IniConfigurationStringParser.Instance);
            // builder.AddNacosV2Configuration(c.GetSection("NacosConfig"), Nacos.YamlParser.YamlConfigurationStringParser.Instance);
        })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });
  1. Modify appsettings.json
{
  "NacosConfig": {
    "Listeners": [
      {
        "Optional": false,
        "DataId": "common",
        "Group": "DEFAULT_GROUP"
      },
      {
        "Optional": false,
        "DataId": "demo",
        "Group": "DEFAULT_GROUP"
      }
    ],    
    "Namespace": "csharp-demo",  // Please set the value of Namespace ID !!!!!!!!
    "ServerAddresses": [ "http://localhost:8848/" ],
    "UserName": "test2",
    "Password": "123456",
    "AccessKey": "",
    "SecretKey": "",
    "EndPoint": "acm.aliyun.com",
    "ConfigFilterAssemblies": ["YouPrefix.AssemblyName"],
    "ConfigFilterExtInfo": "some ext infomation"
  }
}
  1. Use via .NET Core's Way
[ApiController]
[Route("api/[controller]")]
public class ConfigController : ControllerBase
{
    private readonly IConfiguration _configuration;
    private readonly AppSettings _settings;
    private readonly AppSettings _sSettings;
    private readonly AppSettings _mSettings;
    
    public ConfigController(
        IConfiguration configuration,
        IOptions<AppSettings> options,
        IOptionsSnapshot<AppSettings> sOptions,
        IOptionsMonitor<AppSettings> _mOptions
        )
    {
        _logger = logger;
        _configuration = configuration;
        _settings = options.Value;
        _sSettings = sOptions.Value;
        _mSettings = _mOptions.CurrentValue;
    }

    [HttpGet]
    public string Get()
    {
        // ....
       
        return "ok";
    }

}

Service Registration and Discovery

  1. Service Registration

Configure in Program.cs

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        // ...

        services.AddNacosAspNet(Configuration, "nacos");
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // ...
    }
}

Modify appsettings.json

"nacos": {
    "EndPoint": "sub-domain.aliyun.com:8080",
    "ServerAddresses": [ "http://localhost:8848" ],
    "DefaultTimeOut": 15000,
    "Namespace": "cs", // Please set the value of Namespace ID !!!!!!!!
    "ListenInterval": 1000,
    "ServiceName": "App1",
    "GroupName": "DEFAULT_GROUP",
    "ClusterName": "DEFAULT",
    "Ip": "",
    "PreferredNetworks": "", // select an IP that matches the prefix as the service registration IP
    "Port": 0,
    "Weight": 100,
    "RegisterEnabled": true,
    "InstanceEnabled": true,
    "Ephemeral": true,
    "Secure": false,
    "AccessKey": "",
    "SecretKey": "",
    "UserName": "",
    "Password": "",
    "ConfigUseRpc": true,
    "NamingUseRpc": true,
    "NamingLoadCacheAtStart": "",       
    "LBStrategy": "WeightRandom", //WeightRandom WeightRoundRobin
    "Metadata": {
      "aa": "bb",
      "cc": "dd"
    }
  }
  1. Service Discovery
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    private readonly Nacos.V2.INacosNamingService _svc;

    public ValuesController(Nacos.V2.INacosNamingService svc)
    {
        _svc = svc;
    }

    [HttpGet("test")]
    public async Task<IActionResult> Test()
    {        
        // need to know the service name.
        var instance = await _svc.SelectOneHealthyInstance("App2", "DEFAULT_GROUP");
        var host = $"{instance.Ip}:{instance.Port}";

        var baseUrl = instance.Metadata.TryGetValue("secure", out _)
            ? $"https://{host}"
            : $"http://{host}";
                    
        if(string.IsNullOrWhiteSpace(baseUrl))
        {
            return "empty";
        }

        var url = $"{baseUrl}/api/values";

        using (HttpClient client = new HttpClient())
        {
            var result = await client.GetAsync(url);
            return await result.Content.ReadAsStringAsync();
        }
    }
}

More Repositories

1

nacos-docker

This project contains a Docker image meant to facilitate the deployment of Nacos .
Shell
1,405
star
2

nacos-sdk-go

Nacos client in Golang
Go
1,123
star
3

nacos-examples

Nacos Examples
Java
953
star
4

r-nacos

Nacos server re-implemented in Rust.
Rust
812
star
5

nacos-spring-boot-project

Nacos ECO Project for Spring Boot
Java
785
star
6

nacos-spring-project

Nacos ECO Project for Spring Framework
Java
755
star
7

nacos-k8s

This project contains a Nacos Docker image meant to facilitate the deployment of Nacos on Kubernetes using StatefulSets.
Go
595
star
8

nacos-sdk-python

nacos python sdk
Python
373
star
9

nacos-sync

Service Sync component
Java
293
star
10

nacos-sdk-nodejs

nacos node.js sdk client
TypeScript
291
star
11

nacos-sdk-cpp

C++ client for Nacos
C++
125
star
12

nacos-sdk-rust

nacos client for rust
Rust
123
star
13

grpc-java-registry-nacos

gRPC Nacos registry integration
Java
98
star
14

nacos-group.github.io

nacos-group.github.io
MDX
97
star
15

nacos-plugin

A collection of Nacos plug-ins, providing Nacos with pluggable plug-in capabilities, support for user customization and high scalability
Java
91
star
16

nacos-coredns-plugin

Nacos DNS-F Client Based On CoreDNS
Go
83
star
17

nacos-template

nacos-template include PPT template and knote
70
star
18

nginx-nacos-upstream

nginx nacos module. subscribe service and configuration from nacos instead of modifying and reloading nginx.conf
C
66
star
19

nacos-istio

Nacos integrate with Istio as a MCP server
Go
40
star
20

nacos-confd

Go
40
star
21

nacos-controller

nacos k8s controller
Go
25
star
22

dubbo-registry-nacos

Dubbo Registry support for Nacos
14
star
23

nacos-k8s-sync

A component for sync services between Nacos and Kubernetes.
Go
12
star
24

nacos-sdk-lua

Lua
12
star
25

nacos-activity

The documents presented in nacos activities
11
star
26

nacos-sdk-php

PHP
11
star
27

nacos-ctl

The controller command sdk for nacos
Java
7
star
28

logback-adapter

Java
5
star
29

acm2nacos-spring-cloud-example

Java
4
star
30

nacos-tutorial

Nacos ็Ÿฅ่กŒๅฎž้ชŒไป“ๅบ“
2
star
31

acm2nacos-java-example

Java
2
star
32

apollo-2-nacos-migration

Apollo่ฟ็งปๅˆฐNacos็š„่„šๆœฌๅทฅ็จ‹
Java
1
star
33

nacos-logo

The logo files for nacos
1
star