You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

544 lines
19 KiB

2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
3 years ago
2 years ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using Microsoft.AspNetCore.Builder;
  6. using Microsoft.AspNetCore.Cors;
  7. using Microsoft.AspNetCore.Extensions.DependencyInjection;
  8. using Microsoft.Extensions.Configuration;
  9. using Microsoft.Extensions.DependencyInjection;
  10. using Microsoft.Extensions.Hosting;
  11. using Shentun.Peis.EntityFrameworkCore;
  12. using Shentun.Peis.MultiTenancy;
  13. using Volo.Abp.AspNetCore.Mvc.UI.Theme.LeptonXLite;
  14. using Volo.Abp.AspNetCore.Mvc.UI.Theme.LeptonXLite.Bundling;
  15. using Microsoft.OpenApi.Models;
  16. using OpenIddict.Validation.AspNetCore;
  17. using Volo.Abp;
  18. using Volo.Abp.Account;
  19. using Volo.Abp.Account.Web;
  20. using Volo.Abp.AspNetCore.MultiTenancy;
  21. using Volo.Abp.AspNetCore.Mvc;
  22. using Volo.Abp.AspNetCore.Mvc.UI.Bundling;
  23. using Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared;
  24. using Volo.Abp.AspNetCore.Serilog;
  25. using Volo.Abp.Autofac;
  26. using Volo.Abp.Localization;
  27. using Volo.Abp.Modularity;
  28. using Volo.Abp.Swashbuckle;
  29. using Volo.Abp.UI.Navigation.Urls;
  30. using Volo.Abp.VirtualFileSystem;
  31. using Microsoft.AspNetCore.Mvc;
  32. using Microsoft.Extensions.Options;
  33. using System.Reflection;
  34. using Swashbuckle.AspNetCore.SwaggerGen;
  35. using Microsoft.AspNetCore.Mvc.Filters;
  36. using Volo.Abp.AspNetCore.Mvc.Validation;
  37. using Microsoft.Extensions.DependencyInjection.Extensions;
  38. using Volo.Abp.Identity;
  39. using Microsoft.Extensions.FileProviders;
  40. using Microsoft.AspNetCore.Mvc.ApplicationModels;
  41. using Volo.Abp.Settings;
  42. using Volo.Abp.Identity.Settings;
  43. using Microsoft.AspNetCore.Identity;
  44. using Volo.Abp.AspNetCore.Mvc.AntiForgery;
  45. using Microsoft.AspNetCore.Authentication;
  46. using Nito.Disposables.Internals;
  47. using Volo.Abp.AspNetCore.Mvc.ExceptionHandling;
  48. using static IdentityModel.ClaimComparer;
  49. using Microsoft.AspNetCore.Authorization;
  50. using Microsoft.AspNetCore.Diagnostics;
  51. using Microsoft.AspNetCore.Http;
  52. using Shentun.Peis.Filter;
  53. using Shentun.Peis.VirtualPath;
  54. using System.Text.Encodings.Web;
  55. using System.Text.Unicode;
  56. using Volo.Abp.Json;
  57. using Shentun.Utilities;
  58. using Volo.Abp.SecurityLog;
  59. using Volo.Abp.Auditing;
  60. namespace Shentun.Peis;
  61. [DependsOn(
  62. typeof(PeisHttpApiModule),
  63. typeof(AbpAutofacModule),
  64. typeof(AbpAspNetCoreMultiTenancyModule),
  65. typeof(PeisApplicationModule),
  66. typeof(PeisEntityFrameworkCoreModule),
  67. typeof(AbpAspNetCoreMvcUiLeptonXLiteThemeModule),
  68. typeof(AbpAccountWebOpenIddictModule),
  69. typeof(AbpAspNetCoreSerilogModule),
  70. typeof(AbpSwashbuckleModule)
  71. )]
  72. public class PeisHttpApiHostModule : AbpModule
  73. {
  74. public override void PreConfigureServices(ServiceConfigurationContext context)
  75. {
  76. PreConfigure<OpenIddictBuilder>(builder =>
  77. {
  78. builder.AddValidation(options =>
  79. {
  80. options.AddAudiences("Peis");
  81. options.UseLocalServer();
  82. options.UseAspNetCore();
  83. });
  84. });
  85. //重写定义token失效时间 接口返回的是秒
  86. PreConfigure<OpenIddictServerBuilder>(builder =>
  87. {
  88. //builder.SetAccessTokenLifetime(TimeSpan.FromHours(8)).SetRefreshTokenLifetime(TimeSpan.FromDays(15));
  89. builder.SetAccessTokenLifetime(TimeSpan.FromDays(30)).SetRefreshTokenLifetime(TimeSpan.FromDays(60));
  90. });
  91. }
  92. public override void ConfigureServices(ServiceConfigurationContext context)
  93. {
  94. var configuration = context.Services.GetConfiguration();
  95. var hostingEnvironment = context.Services.GetHostingEnvironment();
  96. ConfigureAuthentication(context);
  97. ConfigureBundles();
  98. ConfigureUrls(configuration);
  99. ConfigureConventionalControllers();
  100. ConfigureLocalization();
  101. ConfigureVirtualFileSystem(context);
  102. ConfigureCors(context, configuration);
  103. ConfigureSwaggerServices(context, configuration);
  104. ConfigureJsonOptions(); //全局配置api返回值中的日期默认格式
  105. //密码策略配置
  106. context.Services.Configure<IdentityOptions>(opt =>
  107. {
  108. opt.Password.RequireDigit = false;
  109. opt.Password.RequireLowercase = false;
  110. opt.Password.RequireUppercase = false;
  111. opt.Password.RequireNonAlphanumeric = false;
  112. opt.Password.RequiredLength = 1;
  113. });
  114. //密码策略配置
  115. context.Services.Configure<IdentityOptions>(opt =>
  116. {
  117. opt.Password.RequireDigit = false;
  118. opt.Password.RequireLowercase = false;
  119. opt.Password.RequireUppercase = false;
  120. opt.Password.RequireNonAlphanumeric = false;
  121. opt.Password.RequiredLength = 1;
  122. });
  123. #region 临时去掉日志
  124. //关闭审计日志
  125. Configure<AbpAuditingOptions>(options =>
  126. {
  127. options.IsEnabled = false;
  128. });
  129. //关闭安全日志
  130. Configure<AbpSecurityLogOptions>(options =>
  131. {
  132. options.IsEnabled = false;
  133. });
  134. #endregion
  135. //防伪令牌
  136. //context.Services.Configure<AbpAntiForgeryOptions>(opt =>
  137. //{
  138. // opt.AutoValidate = false;
  139. //});
  140. context.Services.AddMvc(options =>
  141. {
  142. var filterMetadata = options.Filters.FirstOrDefault(x => x is ServiceFilterAttribute attribute && attribute.ServiceType.Equals(typeof(AbpValidationActionFilter)));
  143. options.Filters.Remove(filterMetadata);
  144. options.Filters.Add(typeof(ValidateFilter));
  145. options.Filters.Add(typeof(CustomerExceptionFilterAttribute));
  146. options.Filters.Add(typeof(CustomerActionFilterAttribute));
  147. // options.Filters.ReplaceOne(x => (x as ServiceFilterAttribute)?.ServiceType?.Name == nameof(ExceptionFilterAttribute), new ServiceFilterAttribute(typeof(ABCExceptionFilterAttribute)));
  148. // options.Filters.ReplaceOne(x => (x as ServiceFilterAttribute)?.ServiceType?.Name == nameof(AbpExceptionFilter), new ServiceFilterAttribute(typeof(MyExceptionFilter)));
  149. });
  150. //context.Services.TryAddTransient<IAuthorizationMiddlewareResultHandler, AuthorizationMiddlewareResultHandler>();
  151. ///解除https限制
  152. context.Services.AddOpenIddict()
  153. .AddServer(option =>
  154. {
  155. option.UseAspNetCore().DisableTransportSecurityRequirement();
  156. });
  157. //虚拟目录
  158. context.Services.AddSingleton(new MyFileProvider(configuration["VirtualPath:RealPath"], configuration["VirtualPath:Alias"]));
  159. /*
  160. Configure<AbpAspNetCoreMvcOptions>(options =>
  161. {
  162. options.ConventionalControllers
  163. .Create(typeof(PeisApplicationModule).Assembly, opts =>
  164. {
  165. opts.RootPath = "api/app";
  166. opts.UrlControllerNameNormalizer = (controller) =>
  167. {
  168. return controller.ControllerName;
  169. };
  170. opts.UrlActionNameNormalizer = (action) =>
  171. {
  172. return action.Action.ActionName;
  173. };
  174. });
  175. });
  176. */
  177. }
  178. /// <summary>
  179. /// 全局转换日期格式
  180. /// </summary>
  181. private void ConfigureJsonOptions()
  182. {
  183. //context.Services.AddControllers().AddJsonOptions(options =>
  184. //{
  185. // options.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
  186. // options.JsonSerializerOptions.PropertyNamingPolicy = null;
  187. //});
  188. Configure<JsonOptions>(x =>
  189. {
  190. //x.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
  191. x.JsonSerializerOptions.Converters.Add(new DateTimeJsonConverter());
  192. x.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
  193. });
  194. //Configure<AbpJsonOptions>(x =>
  195. //{
  196. // x.DefaultDateTimeFormat = "yyyy-MM-dd HH:mm:ss";
  197. //});
  198. }
  199. private void ConfigureAuthentication(ServiceConfigurationContext context)
  200. {
  201. context.Services.ForwardIdentityAuthenticationForBearer(OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme);
  202. }
  203. private void ConfigureBundles()
  204. {
  205. Configure<AbpBundlingOptions>(options =>
  206. {
  207. options.StyleBundles.Configure(
  208. LeptonXLiteThemeBundles.Styles.Global,
  209. bundle =>
  210. {
  211. bundle.AddFiles("/global-styles.css");
  212. }
  213. );
  214. });
  215. }
  216. private void ConfigureUrls(IConfiguration configuration)
  217. {
  218. Configure<AppUrlOptions>(options =>
  219. {
  220. options.Applications["MVC"].RootUrl = configuration["App:SelfUrl"];
  221. options.RedirectAllowedUrls.AddRange(configuration["App:RedirectAllowedUrls"].Split(','));
  222. options.Applications["Angular"].RootUrl = configuration["App:ClientUrl"];
  223. options.Applications["Angular"].Urls[AccountUrlNames.PasswordReset] = "account/reset-password";
  224. });
  225. }
  226. private void ConfigureVirtualFileSystem(ServiceConfigurationContext context)
  227. {
  228. var hostingEnvironment = context.Services.GetHostingEnvironment();
  229. if (hostingEnvironment.IsDevelopment())
  230. {
  231. Configure<AbpVirtualFileSystemOptions>(options =>
  232. {
  233. options.FileSets.ReplaceEmbeddedByPhysical<PeisDomainSharedModule>(
  234. Path.Combine(hostingEnvironment.ContentRootPath,
  235. $"..{Path.DirectorySeparatorChar}Shentun.Peis.Domain.Shared"));
  236. options.FileSets.ReplaceEmbeddedByPhysical<PeisDomainModule>(
  237. Path.Combine(hostingEnvironment.ContentRootPath,
  238. $"..{Path.DirectorySeparatorChar}Shentun.Peis.Domain"));
  239. options.FileSets.ReplaceEmbeddedByPhysical<PeisApplicationContractsModule>(
  240. Path.Combine(hostingEnvironment.ContentRootPath,
  241. $"..{Path.DirectorySeparatorChar}Shentun.Peis.Application.Contracts"));
  242. options.FileSets.ReplaceEmbeddedByPhysical<PeisApplicationModule>(
  243. Path.Combine(hostingEnvironment.ContentRootPath,
  244. $"..{Path.DirectorySeparatorChar}Shentun.Peis.Application"));
  245. });
  246. }
  247. }
  248. private void ConfigureConventionalControllers()
  249. {
  250. #region 配置隐藏api
  251. Configure<MvcOptions>(options =>
  252. {
  253. options.Conventions.Add(new ApplicationDescription());
  254. });
  255. #endregion
  256. Configure<AbpAspNetCoreMvcOptions>(options =>
  257. {
  258. options.ConventionalControllers.Create(typeof(PeisApplicationModule).Assembly);
  259. });
  260. }
  261. private static void ConfigureSwaggerServices(ServiceConfigurationContext context, IConfiguration configuration)
  262. {
  263. context.Services.AddAbpSwaggerGenWithOAuth(
  264. configuration["AuthServer:Authority"],
  265. new Dictionary<string, string>
  266. {
  267. {"Peis", "Peis API"}
  268. },
  269. options =>
  270. {
  271. //options.SwaggerDoc("v1", new OpenApiInfo { Title = "Peis API", Version = "v1" });
  272. //options.DocInclusionPredicate((docName, description) => true);
  273. //options.CustomSchemaIds(type => type.FullName);
  274. options.SwaggerDoc("Work", new OpenApiInfo { Title = "业务API", Version = "V1", Description = "业务API" });
  275. options.SwaggerDoc("Sys", new OpenApiInfo { Title = "底层API", Version = "V1", Description = "底层API" });
  276. options.DocInclusionPredicate((docName, description) =>
  277. {
  278. if (!description.TryGetMethodInfo(out MethodInfo method))
  279. {
  280. return false;
  281. }
  282. /*使ApiExplorerSettingsAttribute里面的GroupName进行特性标识
  283. * DeclaringType只能获取controller上的特性
  284. * action的特性为主
  285. * */
  286. var version = method.DeclaringType.GetCustomAttributes(true).OfType<ApiExplorerSettingsAttribute>().Select(m => m.GroupName);
  287. if (version.Any())
  288. {
  289. if (version.Any(v => v == docName))
  290. //选择了sys,并且分组不为User
  291. return true;
  292. }
  293. else
  294. {
  295. if (docName == "Sys")
  296. {
  297. return true;
  298. }
  299. }
  300. //这里获取action的特性
  301. var actionVersion = method.GetCustomAttributes(true).OfType<ApiExplorerSettingsAttribute>().Select(m => m.GroupName);
  302. if (actionVersion.Any())
  303. {
  304. return actionVersion.Any(v => v == docName);
  305. }
  306. return false;
  307. });
  308. });
  309. }
  310. private void ConfigureLocalization()
  311. {
  312. Configure<AbpLocalizationOptions>(options =>
  313. {
  314. options.Languages.Add(new LanguageInfo("ar", "ar", "العربية"));
  315. options.Languages.Add(new LanguageInfo("cs", "cs", "Čeština"));
  316. options.Languages.Add(new LanguageInfo("en", "en", "English"));
  317. options.Languages.Add(new LanguageInfo("en-GB", "en-GB", "English (UK)"));
  318. options.Languages.Add(new LanguageInfo("fi", "fi", "Finnish"));
  319. options.Languages.Add(new LanguageInfo("fr", "fr", "Français"));
  320. options.Languages.Add(new LanguageInfo("hi", "hi", "Hindi", "in"));
  321. options.Languages.Add(new LanguageInfo("is", "is", "Icelandic", "is"));
  322. options.Languages.Add(new LanguageInfo("it", "it", "Italiano", "it"));
  323. options.Languages.Add(new LanguageInfo("hu", "hu", "Magyar"));
  324. options.Languages.Add(new LanguageInfo("pt-BR", "pt-BR", "Português"));
  325. options.Languages.Add(new LanguageInfo("ro-RO", "ro-RO", "Română"));
  326. options.Languages.Add(new LanguageInfo("ru", "ru", "Русский"));
  327. options.Languages.Add(new LanguageInfo("sk", "sk", "Slovak"));
  328. options.Languages.Add(new LanguageInfo("tr", "tr", "Türkçe"));
  329. options.Languages.Add(new LanguageInfo("zh-Hans", "zh-Hans", "简体中文"));
  330. options.Languages.Add(new LanguageInfo("zh-Hant", "zh-Hant", "繁體中文"));
  331. options.Languages.Add(new LanguageInfo("de-DE", "de-DE", "Deutsch", "de"));
  332. options.Languages.Add(new LanguageInfo("es", "es", "Español", "es"));
  333. options.Languages.Add(new LanguageInfo("el", "el", "Ελληνικά"));
  334. });
  335. }
  336. private void ConfigureCors(ServiceConfigurationContext context, IConfiguration configuration)
  337. {
  338. context.Services.AddCors(options =>
  339. {
  340. options.AddDefaultPolicy(builder =>
  341. {
  342. builder
  343. .WithOrigins(
  344. configuration["App:CorsOrigins"]
  345. .Split(",", StringSplitOptions.RemoveEmptyEntries)
  346. .Select(o => o.RemovePostFix("/"))
  347. .ToArray()
  348. )
  349. .WithAbpExposedHeaders()
  350. .SetIsOriginAllowedToAllowWildcardSubdomains()
  351. .AllowAnyHeader()
  352. .AllowAnyMethod()
  353. .AllowCredentials();
  354. });
  355. });
  356. //添加swagger中文注释
  357. context.Services.AddSwaggerGen(options =>
  358. {
  359. //var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
  360. var baseDirectory = AppContext.BaseDirectory;
  361. //Serilog.Log.Information("swagger地址1:" + baseDirectory);
  362. //var baseDirectory2 = Path.GetDirectoryName(typeof(Program).Assembly.Location);
  363. //Serilog.Log.Information("swagger地址2:" + baseDirectory2);
  364. //var baseDirectory3 = AppDomain.CurrentDomain.BaseDirectory;
  365. //Serilog.Log.Information("swagger地址3:" + baseDirectory3);
  366. var commentsFile = Path.Combine(baseDirectory, "Shentun.Peis.Application.xml");
  367. options.IncludeXmlComments(commentsFile, true);
  368. var commentsFileDro = Path.Combine(baseDirectory, "Shentun.Peis.Application.Contracts.xml");
  369. options.IncludeXmlComments(commentsFileDro, true);
  370. var commentsFileapi = Path.Combine(baseDirectory, "Shentun.Peis.HttpApi.xml");
  371. options.IncludeXmlComments(commentsFileapi, true);
  372. });
  373. }
  374. public override void OnApplicationInitialization(ApplicationInitializationContext context)
  375. {
  376. var app = context.GetApplicationBuilder();
  377. var env = context.GetEnvironment();
  378. var configuration = context.GetConfiguration();
  379. //请求错误提示配置
  380. app.UseErrorHandling();
  381. if (env.IsDevelopment())
  382. {
  383. app.UseDeveloperExceptionPage();
  384. }
  385. app.UseAbpRequestLocalization();
  386. if (!env.IsDevelopment())
  387. {
  388. app.UseErrorPage();
  389. }
  390. app.UseCorrelationId();
  391. //var staticFile = new StaticFileOptions();
  392. //var filePath = env.ContentRootPath+"UpLoad\\";
  393. ////var filePath = env.ContentRootPath ;
  394. //staticFile.FileProvider = new PhysicalFileProvider(filePath);
  395. //app.UseStaticFiles(new StaticFileOptions
  396. //{
  397. // FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "UpLoad")),
  398. // RequestPath="/UpLoad"
  399. //});
  400. app.UseStaticFiles();
  401. app.UseStaticFiles(new StaticFileOptions
  402. {
  403. FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "ReportFile")),
  404. RequestPath = "/ReportFile"
  405. });
  406. app.UseStaticFiles(new StaticFileOptions
  407. {
  408. FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "UpLoad")),
  409. RequestPath = "/photo"
  410. });
  411. //虚拟目录
  412. app.UseStaticFiles(new StaticFileOptions
  413. {
  414. FileProvider = new PhysicalFileProvider(configuration["VirtualPath:RealPath"]),
  415. RequestPath = configuration["VirtualPath:RequestPath"]
  416. });
  417. app.UseRouting();
  418. app.UseCors();
  419. app.UseAuthentication();
  420. app.UseAbpOpenIddictValidation();
  421. if (MultiTenancyConsts.IsEnabled)
  422. {
  423. app.UseMultiTenancy();
  424. }
  425. app.UseUnitOfWork();
  426. app.UseAuthorization();
  427. //app.UseMiddleware(typeof(AuthorizationMiddlewareResultHandler));
  428. app.UseSwagger();
  429. app.UseAbpSwaggerUI(c =>
  430. {
  431. //c.SwaggerEndpoint("/swagger/v1/swagger.json", "Peis API");
  432. c.SwaggerEndpoint($"/swagger/Work/swagger.json", "业务API"); //分组显示
  433. c.SwaggerEndpoint($"/swagger/Sys/swagger.json", "底层API"); //分组显示
  434. //c.RoutePrefix = string.Empty; // url 中不显示swagger
  435. var configuration = context.ServiceProvider.GetRequiredService<IConfiguration>();
  436. c.OAuthClientId(configuration["AuthServer:SwaggerClientId"]);
  437. c.OAuthScopes("Peis");
  438. c.DefaultModelExpandDepth(-1);
  439. });
  440. app.UseAuditing();
  441. app.UseAbpSerilogEnrichers();
  442. app.UseConfiguredEndpoints();
  443. }
  444. }