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.Utility.AssemblyHelper; 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; 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()); // 检索程序集信息 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().AddJsonOptions(options => { 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.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.UseMultiTenantMiaoYu(); //异常中间件 app.UseExecutionTimeMiddleware(); //请求耗时中间件 app.UseExceptionMiddleware(); #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();