1-创建一个 WebApi
2- 添加引用
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
{ "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 服务配置配置
{ "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-程序配置
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();
主要配置:
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配置
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; } } }
标签:集成,builder,Nacos,options,Services,using,Configuration,Net6.0 From: https://www.cnblogs.com/ganqiyin/p/17632058.html