123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236 |
- 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<Startup> logger)
- {
- Configuration = configuration;
- Logger = logger;
- }
- public IConfiguration Configuration { get; }
- public ILogger<Startup> 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<CookiePolicyOptions>(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<MvcOptions> filters = new Action<MvcOptions>(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<MacStatusService>();
- 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<TaskLaunchManager>();
- services.AddSingleton<AppletStatusCollection>();
- services.AddSingleton<IEapScoketServer, EapSocketServer>();
- services.AddSingleton<LogHandler>();
- // 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<ModelMappingProfile>(); },
- 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<MacStatusHub>("/eap/hub/macstatus/last");
- routes.MapHub<LogHub>("/eap/hub/macstatus/log");
- });
- if (Configuration["EapSocket"] != null && Convert.ToBoolean(Configuration["EapSocket"]) == true)
- {
- var EapScoket = app.ApplicationServices.GetRequiredService<IEapScoketServer>();
- 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?}");
- });
- }
- }
- }
|