Skip to content

Latest commit

 

History

History
82 lines (64 loc) · 1.59 KB

README.zh-cn.md

File metadata and controls

82 lines (64 loc) · 1.59 KB

nacos-csharp-extensions English

一些基于 nacos-sdk-csharp 的扩展.

功能特性

  • 声明式服务调用工具集成
    1. WebApiClient
    2. WebApiClientCore
    3. Refit
  • 反向代理 YARP 集成
  • 其他..

基本用法

API 定义

// for webapiclient/core
[HttpHost("http://githubsvc")]
public interface IGitHubAPI : IHttpApi
{
    [HttpGet("")]
    Task<string> Get();
}

// for refit
[Headers("User-Agent: Refit Nacos Tests")]
public interface IGitHubAPI
{
    [Get("")]
    Task<HttpResponseMessage> Get();
}

注意: 注册上 nacos 的服务名要是小写的!

配置

// nacos dependency
services.AddNacosV2Naming(x =>
{
});

// for webapiclient/core
services.AddNacosDiscoveryTypedClient<IGitHubAPI>("DEFAULT_GROUP", "DEFAULT");

// for refit
services.AddNacosDiscoveryTypedClient<IGitHubAPI>("DEFAULT_GROUP", "DEFAULT")
        .ConfigureHttpClient(c =>
        {
            // The service name must be lowercase!
            c.BaseAddress = new Uri("http://githubsvc");
            c.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        });

调用

[ApiController]
[Route("[controller]")]
public class ValuesController : ControllerBase
{
    private readonly IGitHubAPI _api;

    public ValuesController(IGitHubAPI api)
    {
        this._api = api;
    }

    [HttpGet]
    public async Task<string> Get()
    {
        var res = await _api.Get().ConfigureAwait(false);

        return $"{res} from IGitHubAPI";
    }
}