Net6.0 集成 Nacos
1-创建一个 WebApi
2- 添加引用
1 2 3 | Install-Package nacos-sdk-csharp -Version 1.3.5 Install-Package nacos-sdk-csharp.AspNetCore -Version 1.3.5 Install-Package nacos-sdk-csharp.Extensions.Configuration -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 | { "Nacos" : { "Listeners" : [ // 对应配置文件 { "Optional" : false , "DataId" : "common" , // 配置名称 "Group" : "DEFAULT_GROUP" // 组名 }, { "Optional" : false , "DataId" : "user" , "Group" : "DEFAULT_GROUP" } ], "DefaultTimeOut" : 15, "ListenInterval" : 1000, "ServiceName" : "userApiSrv" , // 服务名称 "Namespace" : "public" , // 对应的是命名空间的Id "ServerAddresses" : [ "http://ip地址:8848/" ], // 是Nacos的服务器地址,可以添加多个 "UserName" : "nacos" , "Password" : "1Q2w3e4r$" , "ConfigUseRpc" : false , //false-http 协议, true -grpc "NamingUseRpc" : false //false-http 协议, true -grpc }, "Urls" : "http://*:5101" } |
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 39 | { "Serilog" : { "Using" : [ "Serilog.Sinks.Console" , "Serilog.Sinks.Async" , "Serilog.Sinks.File" ], "MinimumLevel" : { "Default" : "Information" , "Override" : { "Microsoft" : "Information" , "System" : "Information" } }, "Enrich" : [ "FromLogContext" , "WithMachineName" , "WithProcessId" , "WithThreadId" ], "Properties" : { "ApplicationName" : "GR.Nacos" }, "WriteTo" : [ { "Name" : "Console" }, { "Name" : "File" , "Args" : { "path" : "Logs/log.log" , "formatter" : "Serilog.Formatting.Json.JsonFormatter, Serilog" , "rollingInterval" : "Day" , "shared" : true , "rollOnFileSizeLimit" : true , "fileSizeLimitBytes" : 102400000, "retainedFileCountLimit" : 365, "outputTemplate" : "{NewLine}{NewLine}Date:{Timestamp:yyyy-MM-dd HH:mm:ss.fff}{NewLine}LogLevel:{Level}{NewLine}Message:{Message}{NewLine}{Exception}" } }, { "Name" : "Seq" , "Args" : { "serverUrl" : "http://localhost:8081" } } ] }, "AllowedHosts" : "*" } |
5-程序配置
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 | 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 MicroSrv.User.HostApi.Models; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddNacosAspNet(builder.Configuration, section: "Nacos" ); builder.Services.Configure<UserInfo>(builder.Configuration.GetSection( "UserInfo" )); 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: "User系统API接口文档" , description: "API接口说明文档" , contact: new NSwag.OpenApiContact { Url = "" , Name = "" }); var app = builder.Build(); app.UseSerilogRequestLogging(); app.UseNSwagger(); app.UseAuthentication(); app.UseAuthorization(); // Configure the HTTP request pipeline. app.MapControllers(); app.Run(); |
主要配置:
1 2 | builder.Services.AddNacosAspNet(builder.Configuration, section: "Nacos" ); builder.Host.UseNacosConfig( "Nacos" , logAction: x => x.AddSerilog()); |
PS:注意一下,我看了很多文档都说,直接使用IConfiguration 文件的 Get 就能获取的 nacos 的配置,这个是错误的,反正我这边测试是行不通的,必须使用 builder.Services.Configure<UserInfo>(builder.Configuration.GetSection("UserInfo")); 然后用 IOptions<UserInfo> options 才能拿到值,错误范例如下:
6-创建一个控制器,开始使用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 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 | using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; using MicroSrv.User.HostApi.Models; using Nacos.V2; using System.Diagnostics; // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace MicroSrv.User.HostApi.Controllers { /// <summary> /// 配置 /// </summary> [Route( "api/v{version:apiVersion}/[controller]" )] [ApiController] public class ConfigController : ControllerBase { private IConfiguration _configuration; private readonly INacosConfigService _nacosConfigSrv; private readonly UserInfo _user; private readonly UserInfo _user2; /// <summary> /// /// </summary> /// <param name="configuration"></param> /// <param name="nacosConfigSrv"></param> /// <param name="options"></param> /// <param name="optionsSnapshot"></param> public ConfigController(IConfiguration configuration , INacosConfigService nacosConfigSrv , IOptions<UserInfo> options , IOptionsSnapshot<UserInfo> optionsSnapshot) { _configuration = configuration; _nacosConfigSrv = nacosConfigSrv; _user = options.Value; _user2 = optionsSnapshot.Value; } /// <summary> /// /// </summary> /// <returns></returns> [HttpGet( "{id}" )] public async Task< string > Get( int id) { string config = "" ; switch (id) { case 1: var sconfig = _configuration.GetSection( "Serilog" ); config = sconfig[ "Using" ]; break ; case 2: config = string .Format( "old-{0},new-{1}" , System.Text.Json.JsonSerializer.Serialize(_user), System.Text.Json.JsonSerializer.Serialize(_user2)); break ; default : config = await _nacosConfigSrv.GetConfig( "common" , Nacos.V2.Common.Constants.DEFAULT_GROUP, 3000); break ; } return config; } } } |
漫漫人生,唯有激流勇进,不畏艰险,奋力拼搏,方能中流击水,抵达光明的彼岸
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
2016-08-15 一个简单的NetCore项目:2 - 登录