using System.Diagnostics; using System.Reflection; using HuanMeng.MiaoYu.Code.MultiTenantUtil; using HuanMeng.DotNetCore.MiddlewareExtend; using HuanMeng.MiaoYu.WebApi.Base; using Microsoft.OpenApi.Models; using HuanMeng.MiaoYu.Code.TencentUtile; using HuanMeng.MiaoYu.Code.Users.UserAccount.VerificationCodeManager; using HuanMeng.MiaoYu.Code.JwtUtil; using Microsoft.AspNetCore.Authentication.JwtBearer; using HuanMeng.DotNetCore.CustomExtension; using HuanMeng.MiaoYu.Code.Cache; using HuanMeng.MiaoYu.Code.Chat; using Serilog; using HuanMeng.MiaoYu.Model.Dto; using System.Text.Json.Serialization; using HuanMeng.DotNetCore.Json; using Newtonsoft.Json.Serialization; using HuanMeng.MiaoYu.Code.SysDictionary; using HuanMeng.MiaoYu.Code.Base; using HuanMeng.MiaoYu.Code.Other; using HuanMeng.DotNetCore.Utility.AssemblyHelper; var builder = WebApplication.CreateBuilder(args); //Log.Logger = new LoggerConfiguration() // .WriteTo.Console() // .WriteTo.File("../output/logs/log-.txt", rollingInterval: RollingInterval.Day) // .CreateLogger(); builder.Host.UseSerilog((context, services, configuration) => configuration .ReadFrom.Configuration(context.Configuration) .ReadFrom.Services(services) .Enrich.FromLogContext()); builder.Services.AddSingleton(typeof(ILogger), serviceProvider => { var loggerFactory = serviceProvider.GetRequiredService(); return loggerFactory.CreateLogger(); }); // 检索程序集信息 AssemblyInfo assemblyInfo = AssemblyInfoHelper.GetAssemblyInfo(); // Add services to the container. builder.Services.AddHttpClient(); builder.Services.AddHttpContextAccessor(); //添加httpContext注入访问 #region 添加跨域 var _myAllowSpecificOrigins = "_myAllowSpecificOrigins"; builder.Services.AddCustomCors(_myAllowSpecificOrigins); #endregion #region automap var mapperDomain = AppDomain.CurrentDomain.GetAssemblies().Where(it => it.FullName.Contains("HuanMeng") || it.FullName.Contains("XLib.")).ToList(); Type type = typeof(ResponseUserInfo); if (type != null) { Assembly assembly = Assembly.GetAssembly(type); if (!mapperDomain.Any(it => it.FullName == assembly.FullName)) { mapperDomain.Add(assembly); } } builder.Services.AddAutoMapper(mapperDomain); #endregion builder.Services.AddControllers() .AddNewtonsoftJson(options => { // 配置 Newtonsoft.Json 选项 options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; // 忽略循环引用 options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();// 首字母小写(驼峰样式) options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";// 时间格式化 #if !DEBUG options.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.None; #endif //options.SerializerSettings.Converters.Add() // 其他配置... }) ; // .AddJsonOptions(options => //{ // //options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve; // //options.JsonSerializerOptions.WriteIndented = true; // options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); // //options.JsonSerializerOptions.PropertyNamingPolicy = null; // options.JsonSerializerOptions.Converters.Add(new CustomDateTimeConverter("yyyy-MM-dd HH:mm:ss")); //}); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(c => { var securityScheme = new OpenApiSecurityScheme { Name = "JWT 身份验证(Authentication)", Description = "请输入登录后获取JWT的**token**", In = ParameterLocation.Header, Type = SecuritySchemeType.Http, Scheme = "bearer", //必须小写 BearerFormat = "JWT", Reference = new OpenApiReference { Id = JwtBearerDefaults.AuthenticationScheme, Type = ReferenceType.SecurityScheme } }; c.AddSecurityDefinition(securityScheme.Reference.Id, securityScheme); c.AddSecurityRequirement(new OpenApiSecurityRequirement { {securityScheme, Array.Empty()} }); c.SwaggerDoc("v1", new OpenApiInfo { Title = "妙语", Version = assemblyInfo.Version, Description = assemblyInfo.Description }); foreach (var assemblies in AppDomain.CurrentDomain.GetAssemblies()) { // 添加 XML 注释文件路径 var xmlFile = $"{assemblies.GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); if (File.Exists(xmlPath)) { c.IncludeXmlComments(xmlPath); } } c.ParameterFilter(); c.RequestBodyFilter(); }); //配置路由选项,使URL全部小写 //builder.Services.AddRouting(options => options.LowercaseUrls = true); //添加多租户 builder.AddMultiTenantMiaoYu(); //添加腾讯云管理 builder.AddTencent(); //添加验证码组件 builder.AddMemoryVerificationCode(); //添加jwt验证 builder.AddJwtConfig(); //添加数据字典 builder.AddDictionaryInfo(); //添加文本审核 builder.AddTextCensor(); //builder.Services.AddMemoryCache(); //builder.Services.AddScoped(); ////builder.Services.AddScoped(); var app = builder.Build(); // Configure the HTTP request pipeline. //if (app.Environment.IsDevelopment()) //{ app.UseSwagger(); app.UseSwaggerUI(c => { c.EnableDeepLinking(); c.DefaultModelsExpandDepth(3); c.DefaultModelExpandDepth(3); c.EnableFilter("true"); //c.RoutePrefix = string.Empty; c.SwaggerEndpoint("/swagger/v1/swagger.json", "寰梦 API V1"); }); //} app.UseSerilogRequestLogging(); app.UseAuthorization(); //自定义初始化 //使用跨域 app.UseCors(_myAllowSpecificOrigins); app.MapControllers(); app.UseStaticFiles();//静态文件访问配置 //数据库中间件 app.UseMultiTenantMiaoYu(); //执行扩展中间件 app.UseMiddlewareAll(); #region 默认请求 app.MapGet("/", () => "请求成功").WithName("默认请求"); var startDateTime = DateTime.Now; var InformationalVersion = Assembly.GetEntryAssembly().GetCustomAttribute().InformationalVersion; Console.WriteLine($"version:{InformationalVersion}"); app.MapGet("/system", () => { using Process currentProcess = Process.GetCurrentProcess(); // CPU使用率 (一般是一个0-100之间的值,但实际是时间占比,需要转换) double cpuUsage = currentProcess.TotalProcessorTime.TotalMilliseconds / Environment.TickCount * 100; // 已用内存 (字节) long memoryUsage = currentProcess.WorkingSet64; return new { msg = $"系统信息:{assemblyInfo.InformationalVersion},启动时间:{startDateTime.ToString("yyyy-MM-dd HH:mm:ss")},已安全运行时间:{DateTime.Now.Subtract(startDateTime).TotalMinutes.ToString("0.##")}分钟", assemblyInfo, startDateTime, MemoryUsage = $"{memoryUsage / (1024.0 * 1024.0):F2}MB", CPUUsage = $"{cpuUsage:F2}%" }; }).WithName("获取系统数据"); #endregion app.Run();