HuanMengProject/src/2-api/HuanMeng.MiaoYu.WebApi/Program.cs
2024-07-15 18:45:49 +08:00

164 lines
5.9 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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<string>()}
});
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<LowercaseParameterFilter>();
c.RequestBodyFilter<LowercaseRequestFilter>();
});
//配置路由选项使URL全部小写
//builder.Services.AddRouting(options => options.LowercaseUrls = true);
//添加多租户
builder.AddMultiTenantMiaoYu();
//添加腾讯云管理
builder.AddTencent();
//添加验证码组件
builder.AddMemoryVerificationCode();
//添加jwt验证
builder.AddJwtConfig();
//builder.Services.AddMemoryCache();
//builder.Services.AddScoped<CharacterInfoBaseCache>();
////builder.Services.AddScoped<ChatBLL>();
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<AssemblyInformationalVersionAttribute>().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();