| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763 |
- using Microsoft.AspNetCore.DataProtection;
- using Microsoft.AspNetCore.Http.Connections;
- using Microsoft.AspNetCore.Http.Features;
- using Microsoft.AspNetCore.ResponseCompression;
- using Microsoft.AspNetCore.Server.Kestrel.Core;
- using Microsoft.Extensions.DependencyInjection.Extensions;
- using NPOI.POIFS.Crypt;
- using OASystem.API.Middlewares;
- using OASystem.API.OAMethodLib;
- using OASystem.API.OAMethodLib.AMapApi;
- using OASystem.API.OAMethodLib.APNs;
- using OASystem.API.OAMethodLib.DeepSeekAPI;
- using OASystem.API.OAMethodLib.GenericSearch;
- using OASystem.API.OAMethodLib.Hotmail;
- using OASystem.API.OAMethodLib.Hub.Hubs;
- using OASystem.API.OAMethodLib.HunYuanAPI;
- using OASystem.API.OAMethodLib.JuHeAPI;
- using OASystem.API.OAMethodLib.QiYeWeChatAPI;
- using OASystem.API.OAMethodLib.Quartz.Jobs;
- using OASystem.API.OAMethodLib.SignalR.HubService;
- using OASystem.Infrastructure.Logging;
- using Quartz;
- using Quartz.Impl;
- using Quartz.Spi;
- using QuzrtzJob.Factory;
- using Serilog.Events;
- using System.IO.Compression;
- using TencentCloud.Common;
- using TencentCloud.Common.Profile;
- using TencentCloud.Hunyuan.V20230901;
- using static OASystem.API.Middlewares.RateLimitMiddleware;
- using OASystem.API.OAMethodLib.MicrosoftGraphMailbox;
- Console.Title = $"FMGJ OASystem Server";
- var builder = WebApplication.CreateBuilder(args);
- var basePath = AppContext.BaseDirectory;
- //寮曞叆閰嶇疆鏂囦欢
- var _config = new ConfigurationBuilder()
- .SetBasePath(basePath)
- .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
- .AddJsonFile("appsettings.Development.json", optional: true, reloadOnChange: true)
- .AddEnvironmentVariables()
- .Build();
- builder.Services.AddSingleton(new AppSettingsHelper(_config));
- //璁剧疆璇锋眰鍙傛暟鍙�涓嶅~
- builder.Services.AddControllers(options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true);
- //璁剧疆璇锋眰鍙傛暟閿欒��榛樿�よ繑鍥炴牸寮�
- builder.Services.AddControllers()
- .ConfigureApiBehaviorOptions(options =>
- {
- options.InvalidModelStateResponseFactory = context =>
- {
- var errors = context.ModelState
- .Where(e => e.Value.Errors.Count > 0)
- .ToDictionary(
- kvp => kvp.Key,
- kvp => kvp.Value.Errors.Select(e => e.ErrorMessage).ToArray()
- );
- var result = new JsonView
- {
- Code = 400,
- Msg = errors.FirstOrDefault().Value.FirstOrDefault() ?? "",
- Data = errors
- };
- return new BadRequestObjectResult(result);
- };
- });
- // Add services to the container.
- builder.Services.AddControllersWithViews();
- builder.Services.AddControllers()
- .AddJsonOptions(options =>
- {
- //绌哄瓧娈典笉鍝嶅簲Response
- //options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
- options.JsonSerializerOptions.Converters.Add(new NullJsonConverter());
- //鏃堕棿鏍煎紡鍖栧搷搴�
- options.JsonSerializerOptions.Converters.Add(new DateTimeJsonConverter("yyyy-MM-dd HH:mm:ss"));
- //decimal 鍥涗綅灏忔暟
- //options.JsonSerializerOptions.Converters.Add(new DecimalConverter(_decimalPlaces)); // 灏嗕繚鐣欏皬鏁颁綅鏁板弬鏁颁紶閫掔粰鑷�瀹氫箟搴忓垪鍖栧櫒
- });
- builder.Services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
- #region 娣诲姞闄愭祦涓�闂翠欢鏈嶅姟娉ㄥ唽
- // 娣诲姞鍐呭瓨缂撳瓨锛堥檺娴侀渶瑕侊級
- builder.Services.AddMemoryCache();
- // 閰嶇疆闄愭祦璁剧疆
- builder.Services.Configure<RateLimitConfig>(
- builder.Configuration.GetSection("RateLimiting"));
- #endregion
- #region Gzip
- builder.Services.AddResponseCompression(options =>
- {
- options.EnableForHttps = true;
- options.Providers.Add<GzipCompressionProvider>();
- });
- builder.Services.Configure<GzipCompressionProviderOptions>(options =>
- {
- options.Level = CompressionLevel.Optimal;
- });
- #endregion
- #region Cors
- builder.Services.AddCors(options =>
- {
- //policy.AddPolicy("Cors", opt => opt
- // //.SetIsOriginAllowed(origin =>
- // //{
- // // // 瀹氫箟鍏佽�哥殑鏉ユ簮鍒楄〃
- // // var allowedOrigins = new List<string>
- // // {
- // // "http://132.232.92.186:9002",
- // // "http://oa.pan-american-intl.com:4399"
- // // };
- // // // 妫€鏌ヨ�锋眰鐨勬潵婧愭槸鍚﹀湪鍏佽�哥殑鍒楄〃涓�
- // // return allowedOrigins.Contains(origin);
- // //})
- // //.AllowAnyOrigin()
- // //.AllowAnyHeader()
- // //.WithMethods("GET", "POST", "HEAD", "PUT", "DELETE", "OPTIONS")
- // //.AllowCredentials());
- // .AllowAnyHeader()
- // .AllowAnyMethod()
- // .AllowCredentials());
- options.AddPolicy("Cors", policy =>
- {
- policy.AllowAnyOrigin()
- .AllowAnyHeader()
- .AllowAnyMethod();
- });
- });
- #endregion
- #region 涓婁紶鏂囦欢
- builder.Services.AddCors(policy =>
- {
- policy.AddPolicy("Cors", opt => opt
- .AllowAnyOrigin()
- .AllowAnyHeader()
- .AllowAnyMethod()
- .WithExposedHeaders("X-Pagination"));
- });
- builder.Services.Configure<FormOptions>(options =>
- {
- options.KeyLengthLimit = int.MaxValue;
- options.ValueLengthLimit = int.MaxValue;
- options.MultipartBodyLengthLimit = int.MaxValue;
- options.MultipartHeadersLengthLimit = int.MaxValue;
- });
- builder.Services.Configure<KestrelServerOptions>(options =>
- {
- options.Limits.MaxRequestBodySize = int.MaxValue;
- options.Limits.MaxRequestBufferSize = int.MaxValue;
- });
- #endregion
- #region 鎺ュ彛鍒嗙粍
- var groups = new List<Tuple<string, string>>
- {
- //new Tuple<string, string>("Group1","鍒嗙粍涓€"),
- //new Tuple<string, string>("Group2","鍒嗙粍浜�")
- };
- #endregion
- #region 娉ㄥ叆鏁版嵁搴�
- #region old
- builder.Services.AddScoped(options =>
- {
- return new SqlSugarClient(new List<ConnectionConfig>()
- {
- new() {
- ConfigId = DBEnum.OA2023DB,
- ConnectionString = _config.GetConnectionString("OA2023DB"),
- DbType = DbType.SqlServer,
- IsAutoCloseConnection = true,
- },
- new()
- {
- ConfigId = DBEnum.OA2014DB,
- ConnectionString = _config.GetConnectionString("OA2014DB"),
- DbType = DbType.SqlServer,
- IsAutoCloseConnection = true },
- }
- , db =>
- {
- // SQL鎵ц�屽畬
- db.Aop.OnLogExecuted = (sql, pars) =>
- {
- // 瓒呰繃1绉�
- if (db.Ado.SqlExecutionTime.TotalSeconds > 1)
- {
- var FirstMethodName = db.Ado.SqlStackTrace.FirstMethodName;
- //鎵ц�屽畬浜嗗彲浠ヨ緭鍑篠QL鎵ц�屾椂闂� (OnLogExecutedDelegate)
- Console.WriteLine("NowTime:" + DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss"));
- Console.WriteLine("MethodName:" + FirstMethodName);
- Console.WriteLine("ElapsedTime:" + db.Ado.SqlExecutionTime.ToString());
- Console.WriteLine("ExecuteSQL:" + sql);
- }
- };
- //SQL鎵ц�屽墠
- db.Aop.OnLogExecuting = (sql, pars) =>
- {
- };
- //SQL鎶ラ敊
- db.Aop.OnError = (exp) =>
- {
- //鑾峰彇鍘熺敓SQL鎺ㄨ崘 5.1.4.63 鎬ц兘OK
- //UtilMethods.GetNativeSql(exp.Sql, exp.Parametres);
- //鑾峰彇鏃犲弬鏁癝QL瀵规€ц兘鏈夊奖鍝嶏紝鐗瑰埆澶х殑SQL鍙傛暟澶氱殑锛岃皟璇曚娇鐢�
- //UtilMethods.GetSqlString(DbType.SqlServer, exp.sql, exp.parameters);
- };
- //淇�鏀筍QL鍜屽弬鏁扮殑鍊�
- db.Aop.OnExecutingChangeSql = (sql, pars) =>
- {
- //sql=newsql
- //foreach(var p in pars) //淇�鏀�
- return new KeyValuePair<string, SugarParameter[]>(sql, pars);
- };
- }
- );
- });
- #endregion
- #endregion
- //#region Identity 閰嶇疆
- //builder.Services.AddDataProtection();
- ////涓嶈�佺敤 AddIdentity 锛� AddIdentity 鏄�浜嶮VC妗嗘灦涓�鐨�
- //builder.Services.AddIdentityCore<User>(opt =>
- //{
- // opt.Password.RequireDigit = false; //鏁板瓧
- // opt.Password.RequireLowercase = false;//灏忓啓瀛楁瘝
- // opt.Password.RequireNonAlphanumeric = false;//鐗规畩绗﹀彿 渚嬪�� 锟�#@锛�
- // opt.Password.RequireUppercase = false; //澶у啓瀛楁瘝
- // opt.Password.RequiredLength = 6;//瀵嗙爜闀垮害 6
- // opt.Password.RequiredUniqueChars = 1;//鐩稿悓瀛楃�﹀彲浠ュ嚭鐜板嚑娆�
- // opt.Lockout.MaxFailedAccessAttempts = 5; //鍏佽�告渶澶氳緭鍏ヤ簲娆$敤鎴峰悕/瀵嗙爜閿欒��
- // opt.Lockout.DefaultLockoutTimeSpan = new TimeSpan(0, 5, 0);//閿佸畾浜斿垎閽�
- // opt.Tokens.PasswordResetTokenProvider = TokenOptions.DefaultEmailProvider; // 淇�鏀瑰瘑鐮佷娇鐢ㄩ偖浠躲€愰獙璇佺爜妯″紡銆�
- // opt.Tokens.EmailConfirmationTokenProvider = TokenOptions.DefaultEmailProvider; ////
- //});
- //var idBuilder = new IdentityBuilder(typeof(User), typeof(UserRole), services);
- //idBuilder.AddEntityFrameworkStores<swapDbContext>().AddDefaultTokenProviders().AddRoleManager<RoleManager<UserRole>>().AddUserManager<UserManager<User>>();
- //#endregion
- #region 娉ㄥ叆Swagger娉ㄩ噴(鍚�鐢�)
- if (AppSettingsHelper.Get("UseSwagger").ToBool())
- {
- builder.Services.AddSwaggerGen(a =>
- {
- a.SwaggerDoc("v1", new OpenApiInfo
- {
- Version = "v1",
- Title = "Api",
- Description = "Api鎺ュ彛鏂囨。"
- });
- foreach (var item in groups)
- {
- a.SwaggerDoc(item.Item1, new OpenApiInfo { Version = item.Item1, Title = item.Item2, Description = $"{item.Item2}鎺ュ彛鏂囨。" });
- }
- a.DocumentFilter<SwaggerApi>();
- a.IncludeXmlComments(Path.Combine(basePath, "OASystem.Api.xml"), true);
- a.IncludeXmlComments(Path.Combine(basePath, "OASystem.Domain.xml"), true);
- a.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
- {
- Description = "Value: Bearer {token}",
- Name = "Authorization",
- In = ParameterLocation.Header,
- Type = SecuritySchemeType.ApiKey,
- Scheme = "Bearer"
- });
- a.AddSecurityRequirement(new OpenApiSecurityRequirement()
- {{
- new OpenApiSecurityScheme
- {
- Reference = new OpenApiReference
- {
- Type = ReferenceType.SecurityScheme,
- Id = "Bearer"
- }, Scheme = "oauth2", Name = "Bearer", In = ParameterLocation.Header }, new List<string>()
- }
- });
- });
- }
- #endregion
- #region 娣诲姞鏍¢獙
- builder.Services.AddTransient<OASystemAuthentication>();
- builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
- .AddJwtBearer(options =>
- {
- options.TokenValidationParameters = new TokenValidationParameters
- {
- ValidateIssuer = true,
- ValidateAudience = true,
- ValidateLifetime = true,
- ValidateIssuerSigningKey = true,
- ValidAudience = "OASystem.com",
- ValidIssuer = "OASystem.com",
- IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["JwtSecurityKey"])),
- ClockSkew = TimeSpan.FromSeconds(30), //杩囨湡鏃堕棿瀹归敊鍊硷紝瑙e喅鏈嶅姟鍣ㄧ��鏃堕棿涓嶅悓姝ラ棶棰橈紙绉掞級
- RequireExpirationTime = true,
- };
- options.Events = new JwtBearerEvents
- {
- OnMessageReceived = context =>
- {
- var path = context.HttpContext.Request.Path;
- //濡傛灉鏄痵ignalr璇锋眰锛岄渶瑕佸皢token杞�瀛橈紝鍚﹀垯JWT鑾峰彇涓嶅埌token銆侽PTIONS璇锋眰闇€瑕佽繃婊ゅ埌锛屽洜涓篛PTIONS璇锋眰鑾峰彇涓嶅埌Token锛岀敤NGINX杩囨护鎺塐PTION璇锋眰.
- if (path.StartsWithSegments("/ChatHub"))
- {
- string accessToken = context.Request.Query["access_token"].ToString();
- if (string.IsNullOrWhiteSpace(accessToken))
- {
- accessToken = context.Request.Headers["Authorization"].ToString();
- }
- context.Token = accessToken.Replace("Bearer ", "").Trim();
- }
- return Task.CompletedTask;
- }
- };
- });
- #endregion
- #region 鍒濆�嬪寲鏃ュ織
- var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
- Log.Logger = new LoggerConfiguration()
- //涓嶈�板綍瀹氭椂璁块棶API
- .Filter.ByIncludingOnly(logEvent =>
- {
- if (logEvent.Properties.TryGetValue("RequestPath", out var pathValue))
- {
- var path = pathValue.ToString().Trim('"');
- return !path.StartsWith("/api/System/PotsMessageUnreadTotalCount");
- }
- return true;
- })
- .MinimumLevel.Information()
- .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
- .MinimumLevel.Override("System", LogEventLevel.Warning)
- .Enrich.FromLogContext()
- .WriteTo.Console()
- .WriteTo.File(Path.Combine("Logs", @"Log.txt"), rollingInterval: RollingInterval.Day)
- .CreateLogger();
- //
- #region 鍑哄叆澧冭垂鐢ㄦ槑缁� 涓撶敤璁板綍鍣�
- // 鎸囧畾纾佺洏缁濆�硅矾寰勶紙绀轰緥锛欴鐩樼殑AppLogs鏂囦欢澶癸級
- var logDirectory = @"D:\OASystem\Logs\EnterExitCost";
- // 鑷�鍔ㄥ垱寤虹洰褰曪紙濡傛灉涓嶅瓨鍦�锛�
- try
- {
- Directory.CreateDirectory(logDirectory);
- Log.Information($"鏃ュ織鐩�褰曞凡鍒涘缓/纭�璁ゅ瓨鍦�: {logDirectory}");
- }
- catch (Exception ex)
- {
- Log.Fatal($"鏃犳硶鍒涘缓鏃ュ織鐩�褰� {logDirectory}: {ex.Message}");
- throw;
- }
- var eec_TextLogger = new LoggerConfiguration()
- .MinimumLevel.Information()
- .WriteTo.File(Path.Combine(logDirectory, "text-records-.txt"), rollingInterval: RollingInterval.Month)
- .CreateLogger();
- #endregion
- #region 鍥㈢粍姝ラ�ゆ搷浣� 涓撶敤璁板綍鍣�
- // 鎸囧畾纾佺洏缁濆�硅矾寰勶紙绀轰緥锛欴鐩樼殑AppLogs鏂囦欢澶癸級
- var groupLogDir = @"D:\OASystem\Logs\GroupStepOP";
- // 鑷�鍔ㄥ垱寤虹洰褰曪紙濡傛灉涓嶅瓨鍦�锛�
- try
- {
- Directory.CreateDirectory(groupLogDir);
- Log.Information($"鏃ュ織鐩�褰曞凡鍒涘缓/纭�璁ゅ瓨鍦�: {groupLogDir}");
- }
- catch (Exception ex)
- {
- Log.Fatal($"鏃犳硶鍒涘缓鏃ュ織鐩�褰� {groupLogDir}: {ex.Message}");
- throw;
- }
- var groupStepOP_TextLogger = new LoggerConfiguration()
- .MinimumLevel.Information()
- .WriteTo.File(Path.Combine(groupLogDir, "text-records-.txt"), rollingInterval: RollingInterval.Month)
- .CreateLogger();
- #endregion
- #region 浠诲姟鍒嗛厤鎿嶄綔 涓撶敤璁板綍鍣�
- // 鎸囧畾纾佺洏缁濆�硅矾寰勶紙绀轰緥锛欴鐩樼殑AppLogs鏂囦欢澶癸級
- var taskLogDir = @"D:\OASystem\Logs\TaskAllocation";
- // 鑷�鍔ㄥ垱寤虹洰褰曪紙濡傛灉涓嶅瓨鍦�锛�
- try
- {
- Directory.CreateDirectory(taskLogDir);
- Log.Information($"鏃ュ織鐩�褰曞凡鍒涘缓/纭�璁ゅ瓨鍦�: {taskLogDir}");
- }
- catch (Exception ex)
- {
- Log.Fatal($"鏃犳硶鍒涘缓鏃ュ織鐩�褰� {taskLogDir}: {ex.Message}");
- throw;
- }
- var task_TextLogger = new LoggerConfiguration()
- .MinimumLevel.Information()
- .WriteTo.File(Path.Combine(taskLogDir, "text-records-.txt"), rollingInterval: RollingInterval.Month)
- .CreateLogger();
- #endregion
- // 閰嶇疆Serilog涓篖og;
- builder.Host.UseSerilog();
- builder.Services.AddSingleton<ITextFileLogger>(new TextFileLogger(eec_TextLogger));
- builder.Services.AddSingleton<IGroupTextFileLogger>(new GroupTextFileLogger(groupStepOP_TextLogger));
- builder.Services.AddSingleton<ITaskTextFileLogger>(new TaskTextFileLogger(task_TextLogger));
- #endregion
- #region 寮曞叆娉ㄥ唽Autofac Module
- builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
- var hostBuilder = builder.Host.ConfigureContainer<ContainerBuilder>(builder =>
- {
- try
- {
- builder.RegisterModule(new AutofacRegister());
- }
- catch (Exception ex)
- {
- throw new Exception(ex.Message + "\n" + ex.InnerException);
- }
- });
- #endregion
- #region AutoMapper
- AutoMapper.IConfigurationProvider config = new MapperConfiguration(cfg =>
- {
- cfg.AddProfile<_baseMappingProfile>();
- });
- builder.Services.AddSingleton(config);
- builder.Services.AddScoped<IMapper, Mapper>();
- #endregion
- #region DeepSeek AI 鏈嶅姟
- // 閰嶇疆HTTP瀹㈡埛绔�锛圖eepSeek 闀胯€楁椂璋冪敤锛岄粯璁� 10 鍒嗛挓锛�
- builder.Services.AddHttpClient<IDeepSeekService, DeepSeekService>(client =>
- client.Timeout = TimeSpan.FromMinutes(10));
- #endregion
- #region Doubao API 鏈嶅姟
- var doubaoSetting = builder.Configuration.GetSection("DouBao").Get<OASystem.API.OAMethodLib.DoubaoAPI.DoubaoSetting>();
- builder.Services.AddSingleton(doubaoSetting);
- builder.Services.AddHttpClient("Doubao", c => c.BaseAddress = new Uri(doubaoSetting.BaseAddress));
- builder.Services.AddScoped<OASystem.API.OAMethodLib.DoubaoAPI.IDoubaoService, OASystem.API.OAMethodLib.DoubaoAPI.DoubaoService>();
- #endregion
- #region 鑱氬悎API 鏈嶅姟
- builder.Services.AddControllersWithViews();
- builder.Services.AddSingleton<IJuHeApiService, JuHeApiService>();
- builder.Services.AddHttpClient("PublicJuHeApi", c => c.BaseAddress = new Uri("http://web.juhe.cn"));
- builder.Services.AddHttpClient("PublicJuHeTranslateApi", c => c.BaseAddress = new Uri("http://apis.juhe.cn"));
- #endregion
- #region 浼佷笟寰�淇�API 鏈嶅姟
- builder.Services.AddControllersWithViews();
- builder.Services.AddSingleton<IQiYeWeChatApiService, QiYeWeChatApiService>();
- builder.Services.AddHttpClient("PublicQiYeWeChatApi", c => c.BaseAddress = new Uri("https://qyapi.weixin.qq.com"));
- #endregion
- #region 娣峰厓API
- // 浠庨厤缃�涓�璇诲彇鑵捐��浜戝瘑閽ヤ俊鎭�锛堣�风‘淇漚ppsettings.json涓�鏈夊�瑰簲閰嶇疆锛�
- var secretId = builder.Configuration["TencentCloud:SecretId"];
- var secretKey = builder.Configuration["TencentCloud:SecretKey"];
- var region = builder.Configuration["TencentCloud:Region"] ?? "ap-guangzhou";
- // 閰嶇疆HttpClientFactory锛圫DK鍐呴儴浼氱敤鍒帮級
- builder.Services.AddHttpClient();
- // 娉ㄥ唽鑵捐��浜慔unyuan Client涓篠ingleton锛堟帹鑽愶級
- builder.Services.AddSingleton(provider =>
- {
- Credential cred = new Credential
- {
- SecretId = secretId,
- SecretKey = secretKey
- };
- ClientProfile clientProfile = new ClientProfile();
- HttpProfile httpProfile = new HttpProfile
- {
- Endpoint = "hunyuan.tencentcloudapi.com",
- Timeout = 60 * 10, // 鍗曚綅绉�
- };
- clientProfile.HttpProfile = httpProfile;
- return new HunyuanClient(cred, region, clientProfile);
- });
- // 娉ㄥ唽鑷�瀹氫箟鏈嶅姟鎺ュ彛鍙婂叾瀹炵幇涓篠coped鐢熷懡鍛ㄦ湡
- builder.Services.AddScoped<IHunyuanService, HunyuanService>();
- // 娉ㄥ唽娣峰厓鏈嶅姟
- //builder.Services.AddHttpClient<IHunyuanService, HunyuanService>(client =>
- //{
- // client.BaseAddress = new Uri("https://hunyuan.ap-chengdu.tencentcloudapi.com/");
- // client.Timeout = TimeSpan.FromSeconds(60);
- //});
- //builder.Services.Configure<HunyuanApiSettings>(builder.Configuration.GetSection("HunyuanApiSettings"));
- #endregion
- #region 鏈夐亾API 鏈嶅姟
- //builder.Services.AddControllersWithViews();
- //builder.Services.AddSingleton<IYouDaoApiService, YouDaoApiService>();
- //builder.Services.AddHttpClient("PublicYouDaoApi", c => c.BaseAddress = new Uri("https://openapi.youdao.com"));
- #endregion
- #region 楂樺痉鍦板浘API 鏈嶅姟
- builder.Services.AddHttpClient<GeocodeService>();
- #endregion
- #region 閫氱敤鎼滅储鏈嶅姟
- builder.Services.AddScoped(typeof(DynamicSearchService<>));
- #endregion
- #region Quartz
- builder.Services.AddSingleton<ISchedulerFactory, StdSchedulerFactory>();
- builder.Services.AddSingleton<QuartzFactory>();
- builder.Services.AddSingleton<ALiYunPostMessageJob>();
- builder.Services.AddSingleton<TaskJob>();
- builder.Services.AddSingleton<TaskNewsFeedJob>();
- builder.Services.AddSingleton<PerformanceJob>();
- builder.Services.AddSingleton<GroupProcessNodeJob>();
- builder.Services.AddSingleton<WeeklyFridayJob>();
- builder.Services.AddSingleton<ProcessAndNotifySummaryJob>();
- //# new business
- builder.Services.AddControllersWithViews();
- builder.Services.AddSingleton<IAPNsService, APNsService>();
- builder.Services.AddSingleton<IJobFactory, IOCJobFactory>();
- #endregion
- #region SignalR
- builder.Services.AddSignalR()
- .AddJsonProtocol(options =>
- {
- options.PayloadSerializerOptions.PropertyNamingPolicy = null;
- });
- builder.Services.TryAddSingleton(typeof(CommonService));
- #endregion
- #region hotmail
- builder.Services.AddScoped<HotmailService>();
- #endregion
- #region Microsoft Graph 閭�绠辨湇鍔�
- builder.Services.Configure<MicrosoftGraphMailboxOptions>(
- builder.Configuration.GetSection(MicrosoftGraphMailboxOptions.SectionName));
- builder.Services.AddHttpClient("MicrosoftGraph", c =>
- {
- c.BaseAddress = new Uri("https://graph.microsoft.com/v1.0/");
- c.Timeout = TimeSpan.FromMinutes(2);
- });
- builder.Services.AddSingleton<IMicrosoftGraphMailboxService, MicrosoftGraphMailboxService>();
- #endregion
- var app = builder.Build();
- //// 1. 寮傚父澶勭悊鍣ㄥ簲璇ュ湪鏈€鏃╃殑浣嶇疆锛堥櫎浜嗘棩蹇楃瓑锛�
- //app.UseExceptionHandler(new ExceptionHandlerOptions
- //{
- // ExceptionHandlingPath = "/Home/Error",
- // AllowStatusCode404Response = true
- //});
- //鑷�瀹氫箟寮傚父涓�闂翠欢
- //app.UseMiddleware<ExceptionHandlingMiddleware>();
- //serilog鏃ュ織 璇锋眰涓�闂寸�¢亾
- app.UseSerilogRequestLogging(options =>
- {
- //options.MessageTemplate = "HTTP {RequestMethod} {RequestPath} from {ClientIP} (UA: {UserAgent}, Referer: {Referer}) - {StatusCode} in {Elapsed} ms";
- options.MessageTemplate = "HTTP {RequestMethod} {RequestPath} from {ClientIP} (UA: {UserAgent}) - {StatusCode} in {Elapsed} ms";
- // 鑷�瀹氫箟鏃ュ織绾у埆
- options.GetLevel = (httpContext, elapsed, ex) =>
- {
- if (ex != null) return LogEventLevel.Error;
- if (httpContext.Response.StatusCode > 499) return LogEventLevel.Error;
- // 瀵瑰仴搴锋�€鏌ョ瓑绔�鐐逛娇鐢ㄦ洿浣庣骇鍒�
- if (httpContext.Request.Path.StartsWithSegments("/health"))
- return LogEventLevel.Debug;
- return LogEventLevel.Information;
- };
- // 涓板瘜鏃ュ織涓婁笅鏂�
- options.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
- {
- // 鑾峰彇瀹㈡埛绔疘P锛堝�勭悊浠g悊鎯呭喌锛�
- var ipAddress = CommonFun.GetClientIpAddress(httpContext);
- var userAgent = CommonFun.DetectOS(httpContext.Request.Headers.UserAgent.ToString());
- // 娣诲姞IP鍜屽叾浠栨湁鐢ㄤ俊鎭�鍒版棩蹇椾笂涓嬫枃
- diagnosticContext.Set("ClientIP", ipAddress);
- diagnosticContext.Set("RequestHost", httpContext.Request.Host.Value);
- diagnosticContext.Set("UserAgent", userAgent);
- diagnosticContext.Set("Referer", httpContext.Request.Headers.Referer.ToString());
- // 瀵逛簬API璇锋眰娣诲姞棰濆�栦俊鎭�
- if (httpContext.Request.Path.StartsWithSegments("/api"))
- {
- diagnosticContext.Set("RequestContentType", httpContext.Request.ContentType);
- diagnosticContext.Set("RequestContentLength", httpContext.Request.ContentLength ?? 0);
- }
- };
- });
- AutofacIocManager.Instance.Container = app.UseHostFiltering().ApplicationServices.GetAutofacRoot();//AutofacIocManager
- // Configure the HTTP request pipeline.
- if (!app.Environment.IsDevelopment())
- {
- app.UseExceptionHandler("/Home/Error");
- }
- app.UseStaticFiles();
- app.UseRouting();
- app.UseCors("Cors"); //Cors
- //app.UseMiddleware<FixedPromptMiddleware>();
- // 瀹氫箟鍏佽�窤PI鐨勮�块棶鏃堕棿娈�
- //var startTime = DateTime.Parse(_config["ApiAccessTime:StartTime"]);
- //var endTime = DateTime.Parse(_config["ApiAccessTime:EndTime"]);
- //app.UseMiddleware<TimeRestrictionMiddleware>(startTime, endTime);
- //鎸囧畾API鎿嶄綔璁板綍淇℃伅
- app.UseMiddleware<RecordAPIOperationMiddleware>();
- app.UseAuthentication(); // 璁よ瘉
- app.UseMiddleware<RateLimitMiddleware>();
- app.UseAuthorization(); // 鎺堟潈
- app.UseWhen(context =>
- context.Request.Path.StartsWithSegments("/api/MarketCustomerResources/QueryNewClientData"),
- branch => branch.UseResponseCompression());
- // 鎺堟潈璺�寰�
- //app.MapGet("generatetoken", c => c.Response.WriteAsync(JWTBearer.GenerateToken(c)));
- #region 鍚�鐢╯waggerUI
- if (AppSettingsHelper.Get("UseSwagger").ToBool())
- {
- app.UseSwagger();
- app.UseSwaggerUI(c =>
- {
- c.SwaggerEndpoint("/swagger/v1/swagger.json", "Ver0.1");
- foreach (var item in groups)
- {
- c.SwaggerEndpoint($"/swagger/{item.Item1}/swagger.json", item.Item2);
- }
- c.RoutePrefix = string.Empty;
- c.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.None);
- c.DefaultModelsExpandDepth(-1);
- //c.EnableFilter();// 娣诲姞鎼滅储鍔熻兘
- //c.EnableDeepLinking(); // 鍚�鐢ㄦ繁搴﹂摼鎺�
- });
- }
- #endregion
- #region Quartz
- //鑾峰彇瀹瑰櫒涓�鐨凲uartzFactory
- var quartz = app.Services.GetRequiredService<QuartzFactory>();
- app.Lifetime.ApplicationStarted.Register(async () =>
- {
- await quartz.Start();
- });
- app.Lifetime.ApplicationStopped.Register(() =>
- {
- //Quzrtz鍏抽棴鏂规硶
- //quartz.Stop();
- });
- #endregion
- #region SignalR
- app.MapHub<ChatHub>("/ChatHub", options =>
- {
- options.Transports =
- HttpTransportType.WebSockets |
- HttpTransportType.LongPolling;
- });
- #endregion
- app.MapControllerRoute(
- name: "default",
- pattern: "{controller=Home}/{action=Index}/{id?}");
- app.Run();
|