Startup.cs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IdentityModel.Tokens.Jwt;
  4. using System.Linq;
  5. using System.Net.Http;
  6. using System.Reflection;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using Cksoft.Data.Repository;
  10. using Cksoft.Unity;
  11. using Cksoft.Unity.Log4NetConfig;
  12. using DllEapBll;
  13. using DllEapBll.Services;
  14. using DllEapBll.SignalR;
  15. using DllEapCommon.Filters;
  16. using DllEapFileUpload;
  17. using DllUnityWebApi;
  18. using Hangfire;
  19. using Hangfire.MemoryStorage;
  20. using IdentityModel;
  21. using IdentityServer4.AccessTokenValidation;
  22. using log4net.AspNetCore;
  23. using Microsoft.AspNetCore.Authorization;
  24. using Microsoft.AspNetCore.Builder;
  25. using Microsoft.AspNetCore.Hosting;
  26. using Microsoft.AspNetCore.Http;
  27. using Microsoft.AspNetCore.Mvc;
  28. using Microsoft.AspNetCore.Mvc.ApplicationParts;
  29. using Microsoft.AspNetCore.Mvc.Controllers;
  30. using Microsoft.AspNetCore.Mvc.Formatters;
  31. using Microsoft.Extensions.Configuration;
  32. using Microsoft.Extensions.DependencyInjection;
  33. using Microsoft.Extensions.Logging;
  34. using Microsoft.IdentityModel.Tokens;
  35. using NLog.Extensions.Logging;
  36. using NLog.Web;
  37. using WebMainFrameForEap.Config;
  38. using WebMainFrameForEap.Filters;
  39. using WebMainFrameForEap.ModelMappings;
  40. using WebMainFrameForEap.ServiceExtensions;
  41. using WebMainFrameForEap.Tasks;
  42. namespace WebMainFrame
  43. {
  44. public class Startup
  45. {
  46. public static SymmetricSecurityKey symKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("d0ecd23c-dfdb-4005-a2ea-0fea210c858a"));
  47. public Startup(IConfiguration configuration, ILogger<Startup> logger)
  48. {
  49. Configuration = configuration;
  50. Logger = logger;
  51. }
  52. public IConfiguration Configuration { get; }
  53. public ILogger<Startup> Logger { get; set; }
  54. // This method gets called by the runtime. Use this method to add services to the container.
  55. public void ConfigureServices(IServiceCollection services)
  56. {
  57. services.Configure<CookiePolicyOptions>(options =>
  58. {
  59. // This lambda determines whether user consent for non-essential cookies is needed for a given request.
  60. options.CheckConsentNeeded = context => true;
  61. options.MinimumSameSitePolicy = SameSiteMode.Lax;
  62. });
  63. Action<MvcOptions> filters = new Action<MvcOptions>(r =>
  64. {
  65. // r.Filters.Add(typeof(WebApiResultMiddleware)); // 格式化 ADT系统 返回数据
  66. r.Filters.Add(typeof(ExceptionFilterFor));
  67. r.Filters.Add(typeof(ButtonFilter));
  68. r.Filters.Add(typeof(QueryStringFilter));
  69. // 设置接收和返回值可以为XML格式
  70. r.InputFormatters.Add(new XmlSerializerInputFormatter(new MvcOptions { }));
  71. r.OutputFormatters.Add(new XmlSerializerOutputFormatter());
  72. });
  73. // 使用Hangfire任务队列
  74. services.AddHangfire(x => x.UseStorage(new MemoryStorage()));
  75. services.AddMvc(filters).SetCompatibilityVersion(CompatibilityVersion.Version_2_1).ConfigureApplicationPartManager(m =>
  76. {
  77. var fea = new ControllerFeature();
  78. var assembly = Assembly.LoadFrom(AppDomain.CurrentDomain.BaseDirectory + "DllEapBll.dll");
  79. var ufpAssembly = Assembly.LoadFrom(AppDomain.CurrentDomain.BaseDirectory + "DllUfpBll.dll");
  80. m.ApplicationParts.Add(new AssemblyPart(assembly));
  81. m.ApplicationParts.Add(new AssemblyPart(ufpAssembly));
  82. m.PopulateFeature(fea);
  83. services.AddSingleton(fea.Controllers.Select(t => t.AsType()).ToArray());
  84. });
  85. // 启用NSwag
  86. services.AddNSwag();
  87. var manager = new ApplicationPartManager();
  88. var homeType = typeof(DllUnityWebApi.UnityWebApiController);
  89. var controllerAssembly = homeType.GetTypeInfo().Assembly;
  90. manager.ApplicationParts.Add(new AssemblyPart(controllerAssembly));
  91. manager.FeatureProviders.Add(new ControllerFeatureProvider());
  92. var feature = new ControllerFeature();
  93. manager.PopulateFeature(feature);
  94. services.AddSingleton(feature.Controllers.Select(t => t.AsType()).ToArray());
  95. AppConfigurtaionServices.Instance = services.BuildServiceProvider();
  96. services.AddCors(options =>
  97. {
  98. options.AddPolicy("all", builder =>
  99. {
  100. builder.AllowAnyOrigin() //允许任何来源的主机访问
  101. .AllowAnyMethod()
  102. .AllowAnyHeader()
  103. .AllowCredentials();//指定处理cookie
  104. });
  105. });
  106. services.AddSingleton<MacStatusService>();
  107. services.AddSignalR(options =>
  108. {
  109. //客户端发保持连接请求到服务端最长间隔,默认30秒,改成4分钟,网页需跟着设置connection.keepAliveIntervalInMilliseconds = 12e4;即2分钟
  110. options.HandshakeTimeout = TimeSpan.FromMinutes(4);
  111. //服务端发保持连接请求到客户端间隔,默认15秒,改成2分钟,网页需跟着设置connection.serverTimeoutInMilliseconds = 24e4;即4分钟
  112. options.KeepAliveInterval = TimeSpan.FromMinutes(2);
  113. });
  114. services.AddSingleton<TaskLaunchManager>();
  115. services.AddSingleton<AppletStatusCollection>();
  116. services.AddSingleton<IEapScoketServer, EapSocketServer>();
  117. services.AddSingleton<LogHandler>();
  118. // IdentityServer4 OAuth2
  119. services.AddAuthentication("Bearer")
  120. .AddJwtBearer("Bearer", options =>
  121. {
  122. //配置id4授权服务器Url
  123. options.Authority = Configuration["Id4:Authority"];
  124. options.RequireHttpsMetadata = false;
  125. //options.MetadataAddress = Configuration["Id4:Authority"] + "/.well-known/openid-configuration";
  126. //options.Configuration = new Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectConfiguration();
  127. //设置当前webapi项目的资源名称为api1
  128. options.TokenValidationParameters = new TokenValidationParameters
  129. {
  130. ValidateAudience = false,
  131. ValidateIssuer = false
  132. };
  133. var handler = new HttpClientHandler();
  134. handler.ClientCertificateOptions = ClientCertificateOption.Manual;
  135. handler.ServerCertificateCustomValidationCallback =
  136. (httpRequestMessage, cert, certChain, policyErrors) =>
  137. {
  138. return true;
  139. };
  140. options.BackchannelHttpHandler = handler;
  141. options.SaveToken = true;
  142. });
  143. //AutoMapper 映射
  144. services.AddAutoMapper(mapperConfiguration => { mapperConfiguration.AddProfile<ModelMappingProfile>(); },
  145. new Assembly[] { typeof(DllEapBll.MailNotice).Assembly,
  146. typeof(DllEapDal.AsmProgramDal).Assembly,
  147. typeof(DllEapEntity.BIHistory).Assembly,
  148. typeof(Analysis2Controller).Assembly}, ServiceLifetime.Singleton);
  149. //Redis
  150. services.AddRedis();
  151. services.AddSingleton(DbFactory.Base("eap"));
  152. services.AddLazyCache();
  153. }
  154. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  155. public void Configure(IApplicationBuilder app, IHostingEnvironment env,
  156. ILoggerFactory factory)
  157. {
  158. NLog.ILogger logger = NLog.LogManager.LoadConfiguration("NLog.config").GetCurrentClassLogger();
  159. NLog.LogManager.Configuration.Variables["connectionString"] = Configuration["eap:ConnectionStrings"];
  160. Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); //避免日志中的中文输出乱码
  161. ILogger mylogger = factory.CreateLogger(typeof(Startup));
  162. AppConfigurtaionServices.MyLog = mylogger;
  163. mylogger.LogError("服务启动成功。");
  164. if (env.IsDevelopment())
  165. {
  166. app.UseDeveloperExceptionPage();
  167. }
  168. else
  169. {
  170. app.UseExceptionHandler("/Home/Error");
  171. // app.UseHsts();
  172. }
  173. // app.UseIdentityServer();
  174. // app.UseHttpsRedirection();
  175. app.UseCors("all");
  176. app.UseStaticFiles();
  177. app.UseCookiePolicy();
  178. app.UseAuthentication();
  179. app.UseNSwag();
  180. app.UseWebSockets();
  181. app.UseHangfireServer();
  182. app.UseHangfireDashboard();
  183. app.UseSignalR(routes =>
  184. {
  185. routes.MapHub<MacStatusHub>("/eap/hub/macstatus/last");
  186. routes.MapHub<LogHub>("/eap/hub/macstatus/log");
  187. });
  188. if (Configuration["EapSocket"] != null && Convert.ToBoolean(Configuration["EapSocket"]) == true)
  189. {
  190. var EapScoket = app.ApplicationServices.GetRequiredService<IEapScoketServer>();
  191. string errorinfo = "";
  192. EapScoket.Start(ref errorinfo);
  193. mylogger.LogError(errorinfo);
  194. }
  195. // 启动定时任务
  196. TaskLauncher.Start(app).Wait();
  197. app.UseMvc(routes =>
  198. {
  199. routes.MapRoute(
  200. name: "default",
  201. template: "{controller=Home}/{action=Index}/{id?}");
  202. routes.MapRoute(
  203. name: "areaRoute",
  204. template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
  205. });
  206. }
  207. }
  208. }