using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Net.Http; using System.Reflection; using System.Text; using System.Threading.Tasks; using Cksoft.Data.Repository; using Cksoft.Unity; using Cksoft.Unity.Log4NetConfig; using DllEapBll; using DllEapBll.Services; using DllEapBll.SignalR; using DllEapCommon.Filters; using DllEapFileUpload; using DllUnityWebApi; using Hangfire; using Hangfire.MemoryStorage; using IdentityModel; using IdentityServer4.AccessTokenValidation; using log4net.AspNetCore; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ApplicationParts; using Microsoft.AspNetCore.Mvc.Controllers; using Microsoft.AspNetCore.Mvc.Formatters; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.IdentityModel.Tokens; using NLog.Extensions.Logging; using NLog.Web; using WebMainFrameForEap.Config; using WebMainFrameForEap.Filters; using WebMainFrameForEap.ModelMappings; using WebMainFrameForEap.ServiceExtensions; using WebMainFrameForEap.Tasks; namespace WebMainFrame { public class Startup { public static SymmetricSecurityKey symKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("d0ecd23c-dfdb-4005-a2ea-0fea210c858a")); public Startup(IConfiguration configuration, ILogger logger) { Configuration = configuration; Logger = logger; } public IConfiguration Configuration { get; } public ILogger Logger { get; set; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.Lax; }); Action filters = new Action(r => { // r.Filters.Add(typeof(WebApiResultMiddleware)); // 格式化 ADT系统 返回数据 r.Filters.Add(typeof(ExceptionFilterFor)); r.Filters.Add(typeof(ButtonFilter)); r.Filters.Add(typeof(QueryStringFilter)); // 设置接收和返回值可以为XML格式 r.InputFormatters.Add(new XmlSerializerInputFormatter(new MvcOptions { })); r.OutputFormatters.Add(new XmlSerializerOutputFormatter()); }); // 使用Hangfire任务队列 services.AddHangfire(x => x.UseStorage(new MemoryStorage())); services.AddMvc(filters).SetCompatibilityVersion(CompatibilityVersion.Version_2_1).ConfigureApplicationPartManager(m => { var fea = new ControllerFeature(); var assembly = Assembly.LoadFrom(AppDomain.CurrentDomain.BaseDirectory + "DllEapBll.dll"); var ufpAssembly = Assembly.LoadFrom(AppDomain.CurrentDomain.BaseDirectory + "DllUfpBll.dll"); m.ApplicationParts.Add(new AssemblyPart(assembly)); m.ApplicationParts.Add(new AssemblyPart(ufpAssembly)); m.PopulateFeature(fea); services.AddSingleton(fea.Controllers.Select(t => t.AsType()).ToArray()); }); // 启用NSwag services.AddNSwag(); var manager = new ApplicationPartManager(); var homeType = typeof(DllUnityWebApi.UnityWebApiController); var controllerAssembly = homeType.GetTypeInfo().Assembly; manager.ApplicationParts.Add(new AssemblyPart(controllerAssembly)); manager.FeatureProviders.Add(new ControllerFeatureProvider()); var feature = new ControllerFeature(); manager.PopulateFeature(feature); services.AddSingleton(feature.Controllers.Select(t => t.AsType()).ToArray()); AppConfigurtaionServices.Instance = services.BuildServiceProvider(); services.AddCors(options => { options.AddPolicy("all", builder => { builder.AllowAnyOrigin() //允许任何来源的主机访问 .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials();//指定处理cookie }); }); services.AddSingleton(); services.AddSignalR(options => { //客户端发保持连接请求到服务端最长间隔,默认30秒,改成4分钟,网页需跟着设置connection.keepAliveIntervalInMilliseconds = 12e4;即2分钟 options.HandshakeTimeout = TimeSpan.FromMinutes(4); //服务端发保持连接请求到客户端间隔,默认15秒,改成2分钟,网页需跟着设置connection.serverTimeoutInMilliseconds = 24e4;即4分钟 options.KeepAliveInterval = TimeSpan.FromMinutes(2); }); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); // IdentityServer4 OAuth2 services.AddAuthentication("Bearer") .AddJwtBearer("Bearer", options => { //配置id4授权服务器Url options.Authority = Configuration["Id4:Authority"]; options.RequireHttpsMetadata = false; //options.MetadataAddress = Configuration["Id4:Authority"] + "/.well-known/openid-configuration"; //options.Configuration = new Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectConfiguration(); //设置当前webapi项目的资源名称为api1 options.TokenValidationParameters = new TokenValidationParameters { ValidateAudience = false, ValidateIssuer = false }; var handler = new HttpClientHandler(); handler.ClientCertificateOptions = ClientCertificateOption.Manual; handler.ServerCertificateCustomValidationCallback = (httpRequestMessage, cert, certChain, policyErrors) => { return true; }; options.BackchannelHttpHandler = handler; options.SaveToken = true; }); //AutoMapper 映射 services.AddAutoMapper(mapperConfiguration => { mapperConfiguration.AddProfile(); }, new Assembly[] { typeof(DllEapBll.MailNotice).Assembly, typeof(DllEapDal.AsmProgramDal).Assembly, typeof(DllEapEntity.BIHistory).Assembly, typeof(Analysis2Controller).Assembly}, ServiceLifetime.Singleton); //Redis services.AddRedis(); services.AddSingleton(DbFactory.Base("eap")); services.AddLazyCache(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory factory) { NLog.ILogger logger = NLog.LogManager.LoadConfiguration("NLog.config").GetCurrentClassLogger(); NLog.LogManager.Configuration.Variables["connectionString"] = Configuration["eap:ConnectionStrings"]; Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); //避免日志中的中文输出乱码 ILogger mylogger = factory.CreateLogger(typeof(Startup)); AppConfigurtaionServices.MyLog = mylogger; mylogger.LogError("服务启动成功。"); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); // app.UseHsts(); } // app.UseIdentityServer(); // app.UseHttpsRedirection(); app.UseCors("all"); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseAuthentication(); app.UseNSwag(); app.UseWebSockets(); app.UseHangfireServer(); app.UseHangfireDashboard(); app.UseSignalR(routes => { routes.MapHub("/eap/hub/macstatus/last"); routes.MapHub("/eap/hub/macstatus/log"); }); if (Configuration["EapSocket"] != null && Convert.ToBoolean(Configuration["EapSocket"]) == true) { var EapScoket = app.ApplicationServices.GetRequiredService(); string errorinfo = ""; EapScoket.Start(ref errorinfo); mylogger.LogError(errorinfo); } // 启动定时任务 TaskLauncher.Start(app).Wait(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); routes.MapRoute( name: "areaRoute", template: "{area:exists}/{controller=Home}/{action=Index}/{id?}"); }); } } }