using System.Text; using Autofac; using Autofac.Extensions.DependencyInjection; using Entity.Dto.Resp; using HybirdFrameworkCore.Autofac; using HybirdFrameworkCore.AutoTask; using HybirdFrameworkCore.Configuration; using HybirdFrameworkCore.Entity; using HybirdFrameworkCore.Job; using HybirdFrameworkCore.Redis; using log4net; using Mapster; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.IdentityModel.Tokens; using Service.Cloud.Client; using Service.Execute; using Service.FireControl.Client; using Service.Plc.Client; using Service.RealTime; using SqlSugar; using SqlSugar.IOC; var builder = WebApplication.CreateBuilder(args); var log = LogManager.GetLogger(typeof(Program)); builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory()); builder.Host.ConfigureContainer(cb => { cb.Register(c => { var db = new SqlSugarScope(new ConnectionConfig { ConfigId = AppSettingsConstVars.ConfigId, ConnectionString = AppSettingsConstVars.DbSqlConnection, // 设置数据库连接字符串 DbType = AppSettingsConstVars.DbDbType == IocDbType.MySql.ToString() ? DbType.MySql : DbType.SqlServer, IsAutoCloseConnection = true, InitKeyType = InitKeyType.Attribute // 如果使用实体类的属性进行主键标识,请设置为 InitKeyType.Attr }, c => { c.Aop.OnLogExecuting = (sql, pars) => { string nativeSql = UtilMethods.GetNativeSql(sql, pars); log.Info(nativeSql); }; }); return db; }).As().SingleInstance(); cb.RegisterModule(new AutofacModuleRegister()); }); // 注册自定义映射 var mapper = new SysMenuMapper(); mapper.Register(TypeAdapterConfig.GlobalSettings); //在 Autofac 容器中注册IHttpContextAccessor 服务 builder.Services.AddHttpContextAccessor(); //跨域 builder.Services.AddCors(options => { options.AddPolicy (name: "myCors", builde => { builde.WithOrigins("*", "*", "*") .AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod(); } ); }); //redis var redisConnectionString = AppSettingsHelper.GetContent("Redis", "Connection"); var instanceName = AppSettingsHelper.GetContent("Redis", "InstanceName"); //默认数据库 var defaultDb = int.Parse(AppSettingsHelper.GetContent("Redis", "DefaultDB") ?? "0"); if (redisConnectionString != null && instanceName != null) builder.Services.AddSingleton(new RedisHelper(redisConnectionString, instanceName, defaultDb)); builder.Services.AddControllers().AddJsonOptions(configure => { configure.JsonSerializerOptions.Converters.Add(new DatetimeJsonConverter()); // configure.JsonSerializerOptions.Converters.Add(new LongJsonConverter()); }); builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Logging.AddLog4Net("log4net.config"); builder.Services.AddSwaggerGen(c => { var basePath = Path.GetDirectoryName(AppContext.BaseDirectory); //c.IncludeXmlComments(Path.Combine(basePath, Assembly.GetExecutingAssembly().GetName().Name+".xml"), true); c.IncludeXmlComments(Path.Combine(basePath, "WebStarter.xml"), true); c.IncludeXmlComments(Path.Combine(basePath, "Entity.xml"), true); c.IncludeXmlComments(Path.Combine(basePath, "HybirdFrameworkCore.xml"), true); }); bool.TryParse(AppSettingsHelper.GetContent("SignalR", "Enabled"), out var signalrEnabled); if (signalrEnabled) { builder.Services.AddSignalR(options => { options.EnableDetailedErrors = true; options.KeepAliveInterval = TimeSpan.FromMinutes(1); }); } // 添加jwt验证 var securityKey = AppSettingsHelper.GetContent("TokenOptions", "SecurityKey"); var audience = AppSettingsHelper.GetContent("TokenOptions", "Audience"); var issuer = AppSettingsHelper.GetContent("TokenOptions", "Issuer"); builder.Services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(options => //配置鉴权逻辑 { options.TokenValidationParameters = new TokenValidationParameters { ValidIssuer = issuer, ValidAudience = audience, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(securityKey)), ValidateLifetime = false }; }); var app = builder.Build(); // Configure the HTTP request pipeline. app.UseSwagger(); app.UseSwaggerUI(); app.UseStaticFiles(); app.UseAuthorization(); app.UseCors("myCors"); app.MapControllers(); if (signalrEnabled) { app.MapHub("/realtime"); } var list = AppSettingsHelper.GetContent("Kestrel", "Endpoints", "http", "Url"); foreach (var s in list.Split(";")) { log.Info($"use url={s}"); app.Urls.Add(s); } AppInfo.Container = app.Services.GetAutofacRoot(); //云平台 if (AppSettingsHelper.GetBool("cloud", "enable")) { CloudClientMgr.Init(); } //PLC if (AppSettingsHelper.GetBool("plc", "enable")) { PlcMgr.Init(); } //启动换电流程 if (AppSettingsHelper.GetBool("swap", "enable")) { StationSoftMgr.SwappingStateMachineStart(); } //消防 if (AppSettingsHelper.GetBool("fire", "enable")) { FireControlMgr.Init(); } TaskInit.Init(); QuartzSchedulerFactory.Init(); app.Lifetime.ApplicationStopping.Register(QuartzSchedulerFactory.Shutdown); app.Run();