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.

445 lines
16 KiB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 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 TencentCloud.Dts.V20211206.Models;
  37. using Volo.Abp.AspNetCore.Mvc.Validation;
  38. using Microsoft.Extensions.DependencyInjection.Extensions;
  39. using Volo.Abp.Identity;
  40. using Microsoft.Extensions.FileProviders;
  41. using Microsoft.AspNetCore.Mvc.ApplicationModels;
  42. using Volo.Abp.Settings;
  43. using Volo.Abp.Identity.Settings;
  44. using Microsoft.AspNetCore.Identity;
  45. using Volo.Abp.AspNetCore.Mvc.AntiForgery;
  46. using Microsoft.AspNetCore.Authentication;
  47. using Nito.Disposables.Internals;
  48. using Volo.Abp.AspNetCore.Mvc.ExceptionHandling;
  49. using static IdentityModel.ClaimComparer;
  50. using Microsoft.AspNetCore.Authorization;
  51. using Microsoft.AspNetCore.Diagnostics;
  52. using Microsoft.AspNetCore.Http;
  53. using Shentun.Peis.Filter;
  54. namespace Shentun.Peis;
  55. [DependsOn(
  56. typeof(PeisHttpApiModule),
  57. typeof(AbpAutofacModule),
  58. typeof(AbpAspNetCoreMultiTenancyModule),
  59. typeof(PeisApplicationModule),
  60. typeof(PeisEntityFrameworkCoreModule),
  61. typeof(AbpAspNetCoreMvcUiLeptonXLiteThemeModule),
  62. typeof(AbpAccountWebOpenIddictModule),
  63. typeof(AbpAspNetCoreSerilogModule),
  64. typeof(AbpSwashbuckleModule)
  65. )]
  66. public class PeisHttpApiHostModule : AbpModule
  67. {
  68. public override void PreConfigureServices(ServiceConfigurationContext context)
  69. {
  70. PreConfigure<OpenIddictBuilder>(builder =>
  71. {
  72. builder.AddValidation(options =>
  73. {
  74. options.AddAudiences("Peis");
  75. options.UseLocalServer();
  76. options.UseAspNetCore();
  77. });
  78. });
  79. //重写定义token失效时间 接口返回的是秒
  80. PreConfigure<OpenIddictServerBuilder>(builder =>
  81. {
  82. builder.SetAccessTokenLifetime(TimeSpan.FromHours(8)).SetRefreshTokenLifetime(TimeSpan.FromDays(15));
  83. });
  84. }
  85. public override void ConfigureServices(ServiceConfigurationContext context)
  86. {
  87. var configuration = context.Services.GetConfiguration();
  88. var hostingEnvironment = context.Services.GetHostingEnvironment();
  89. ConfigureAuthentication(context);
  90. ConfigureBundles();
  91. ConfigureUrls(configuration);
  92. ConfigureConventionalControllers();
  93. ConfigureLocalization();
  94. ConfigureVirtualFileSystem(context);
  95. ConfigureCors(context, configuration);
  96. ConfigureSwaggerServices(context, configuration);
  97. //密码策略配置
  98. context.Services.Configure<IdentityOptions>(opt =>
  99. {
  100. opt.Password.RequireDigit = false;
  101. opt.Password.RequireLowercase = false;
  102. opt.Password.RequireUppercase = false;
  103. opt.Password.RequireNonAlphanumeric = false;
  104. opt.Password.RequiredLength = 6;
  105. });
  106. //防伪令牌
  107. //context.Services.Configure<AbpAntiForgeryOptions>(opt =>
  108. //{
  109. // opt.AutoValidate = false;
  110. //});
  111. context.Services.AddMvc(options =>
  112. {
  113. var filterMetadata = options.Filters.FirstOrDefault(x => x is ServiceFilterAttribute attribute && attribute.ServiceType.Equals(typeof(AbpValidationActionFilter)));
  114. // 移除 AbpValidationActionFilter
  115. options.Filters.Remove(filterMetadata);
  116. options.Filters.Add(typeof(CustomerExceptionFilterAttribute));
  117. options.Filters.Add(typeof(CustomerActionFilterAttribute));
  118. // options.Filters.ReplaceOne(x => (x as ServiceFilterAttribute)?.ServiceType?.Name == nameof(ExceptionFilterAttribute), new ServiceFilterAttribute(typeof(ABCExceptionFilterAttribute)));
  119. // options.Filters.ReplaceOne(x => (x as ServiceFilterAttribute)?.ServiceType?.Name == nameof(AbpExceptionFilter), new ServiceFilterAttribute(typeof(MyExceptionFilter)));
  120. });
  121. //context.Services.TryAddTransient<IAuthorizationMiddlewareResultHandler, AuthorizationMiddlewareResultHandler>();
  122. ///解除https限制
  123. context.Services.AddOpenIddict()
  124. .AddServer(option =>
  125. {
  126. option.UseAspNetCore().DisableTransportSecurityRequirement();
  127. });
  128. }
  129. private void ConfigureAuthentication(ServiceConfigurationContext context)
  130. {
  131. context.Services.ForwardIdentityAuthenticationForBearer(OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme);
  132. }
  133. private void ConfigureBundles()
  134. {
  135. Configure<AbpBundlingOptions>(options =>
  136. {
  137. options.StyleBundles.Configure(
  138. LeptonXLiteThemeBundles.Styles.Global,
  139. bundle =>
  140. {
  141. bundle.AddFiles("/global-styles.css");
  142. }
  143. );
  144. });
  145. }
  146. private void ConfigureUrls(IConfiguration configuration)
  147. {
  148. Configure<AppUrlOptions>(options =>
  149. {
  150. options.Applications["MVC"].RootUrl = configuration["App:SelfUrl"];
  151. options.RedirectAllowedUrls.AddRange(configuration["App:RedirectAllowedUrls"].Split(','));
  152. options.Applications["Angular"].RootUrl = configuration["App:ClientUrl"];
  153. options.Applications["Angular"].Urls[AccountUrlNames.PasswordReset] = "account/reset-password";
  154. });
  155. }
  156. private void ConfigureVirtualFileSystem(ServiceConfigurationContext context)
  157. {
  158. var hostingEnvironment = context.Services.GetHostingEnvironment();
  159. if (hostingEnvironment.IsDevelopment())
  160. {
  161. Configure<AbpVirtualFileSystemOptions>(options =>
  162. {
  163. options.FileSets.ReplaceEmbeddedByPhysical<PeisDomainSharedModule>(
  164. Path.Combine(hostingEnvironment.ContentRootPath,
  165. $"..{Path.DirectorySeparatorChar}Shentun.Peis.Domain.Shared"));
  166. options.FileSets.ReplaceEmbeddedByPhysical<PeisDomainModule>(
  167. Path.Combine(hostingEnvironment.ContentRootPath,
  168. $"..{Path.DirectorySeparatorChar}Shentun.Peis.Domain"));
  169. options.FileSets.ReplaceEmbeddedByPhysical<PeisApplicationContractsModule>(
  170. Path.Combine(hostingEnvironment.ContentRootPath,
  171. $"..{Path.DirectorySeparatorChar}Shentun.Peis.Application.Contracts"));
  172. options.FileSets.ReplaceEmbeddedByPhysical<PeisApplicationModule>(
  173. Path.Combine(hostingEnvironment.ContentRootPath,
  174. $"..{Path.DirectorySeparatorChar}Shentun.Peis.Application"));
  175. });
  176. }
  177. }
  178. private void ConfigureConventionalControllers()
  179. {
  180. #region 配置隐藏api
  181. Configure<MvcOptions>(options =>
  182. {
  183. options.Conventions.Add(new ApplicationDescription());
  184. });
  185. #endregion
  186. Configure<AbpAspNetCoreMvcOptions>(options =>
  187. {
  188. options.ConventionalControllers.Create(typeof(PeisApplicationModule).Assembly);
  189. });
  190. }
  191. private static void ConfigureSwaggerServices(ServiceConfigurationContext context, IConfiguration configuration)
  192. {
  193. context.Services.AddAbpSwaggerGenWithOAuth(
  194. configuration["AuthServer:Authority"],
  195. new Dictionary<string, string>
  196. {
  197. {"Peis", "Peis API"}
  198. },
  199. options =>
  200. {
  201. //options.SwaggerDoc("v1", new OpenApiInfo { Title = "Peis API", Version = "v1" });
  202. //options.DocInclusionPredicate((docName, description) => true);
  203. //options.CustomSchemaIds(type => type.FullName);
  204. options.SwaggerDoc("Work", new OpenApiInfo { Title = "业务API", Version = "V1", Description = "业务API" });
  205. options.SwaggerDoc("Sys", new OpenApiInfo { Title = "底层API", Version = "V1", Description = "底层API" });
  206. options.DocInclusionPredicate((docName, description) =>
  207. {
  208. if (!description.TryGetMethodInfo(out MethodInfo method))
  209. {
  210. return false;
  211. }
  212. /*使ApiExplorerSettingsAttribute里面的GroupName进行特性标识
  213. * DeclaringType只能获取controller上的特性
  214. * action的特性为主
  215. * */
  216. var version = method.DeclaringType.GetCustomAttributes(true).OfType<ApiExplorerSettingsAttribute>().Select(m => m.GroupName);
  217. if (version.Any())
  218. {
  219. if (version.Any(v => v == docName))
  220. //选择了sys,并且分组不为User
  221. return true;
  222. }
  223. else
  224. {
  225. if (docName == "Sys")
  226. {
  227. return true;
  228. }
  229. }
  230. //这里获取action的特性
  231. var actionVersion = method.GetCustomAttributes(true).OfType<ApiExplorerSettingsAttribute>().Select(m => m.GroupName);
  232. if (actionVersion.Any())
  233. {
  234. return actionVersion.Any(v => v == docName);
  235. }
  236. return false;
  237. });
  238. });
  239. }
  240. private void ConfigureLocalization()
  241. {
  242. Configure<AbpLocalizationOptions>(options =>
  243. {
  244. options.Languages.Add(new LanguageInfo("ar", "ar", "العربية"));
  245. options.Languages.Add(new LanguageInfo("cs", "cs", "Čeština"));
  246. options.Languages.Add(new LanguageInfo("en", "en", "English"));
  247. options.Languages.Add(new LanguageInfo("en-GB", "en-GB", "English (UK)"));
  248. options.Languages.Add(new LanguageInfo("fi", "fi", "Finnish"));
  249. options.Languages.Add(new LanguageInfo("fr", "fr", "Français"));
  250. options.Languages.Add(new LanguageInfo("hi", "hi", "Hindi", "in"));
  251. options.Languages.Add(new LanguageInfo("is", "is", "Icelandic", "is"));
  252. options.Languages.Add(new LanguageInfo("it", "it", "Italiano", "it"));
  253. options.Languages.Add(new LanguageInfo("hu", "hu", "Magyar"));
  254. options.Languages.Add(new LanguageInfo("pt-BR", "pt-BR", "Português"));
  255. options.Languages.Add(new LanguageInfo("ro-RO", "ro-RO", "Română"));
  256. options.Languages.Add(new LanguageInfo("ru", "ru", "Русский"));
  257. options.Languages.Add(new LanguageInfo("sk", "sk", "Slovak"));
  258. options.Languages.Add(new LanguageInfo("tr", "tr", "Türkçe"));
  259. options.Languages.Add(new LanguageInfo("zh-Hans", "zh-Hans", "简体中文"));
  260. options.Languages.Add(new LanguageInfo("zh-Hant", "zh-Hant", "繁體中文"));
  261. options.Languages.Add(new LanguageInfo("de-DE", "de-DE", "Deutsch", "de"));
  262. options.Languages.Add(new LanguageInfo("es", "es", "Español", "es"));
  263. options.Languages.Add(new LanguageInfo("el", "el", "Ελληνικά"));
  264. });
  265. }
  266. private void ConfigureCors(ServiceConfigurationContext context, IConfiguration configuration)
  267. {
  268. context.Services.AddCors(options =>
  269. {
  270. options.AddDefaultPolicy(builder =>
  271. {
  272. builder
  273. .WithOrigins(
  274. configuration["App:CorsOrigins"]
  275. .Split(",", StringSplitOptions.RemoveEmptyEntries)
  276. .Select(o => o.RemovePostFix("/"))
  277. .ToArray()
  278. )
  279. .WithAbpExposedHeaders()
  280. .SetIsOriginAllowedToAllowWildcardSubdomains()
  281. .AllowAnyHeader()
  282. .AllowAnyMethod()
  283. .AllowCredentials();
  284. });
  285. });
  286. //添加swagger中文注释
  287. context.Services.AddSwaggerGen(options =>
  288. {
  289. //var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
  290. var baseDirectory = AppContext.BaseDirectory;
  291. //Serilog.Log.Information("swagger地址1:" + baseDirectory);
  292. //var baseDirectory2 = Path.GetDirectoryName(typeof(Program).Assembly.Location);
  293. //Serilog.Log.Information("swagger地址2:" + baseDirectory2);
  294. //var baseDirectory3 = AppDomain.CurrentDomain.BaseDirectory;
  295. //Serilog.Log.Information("swagger地址3:" + baseDirectory3);
  296. var commentsFile = Path.Combine(baseDirectory, "Shentun.Peis.Application.xml");
  297. options.IncludeXmlComments(commentsFile, true);
  298. var commentsFileDro = Path.Combine(baseDirectory, "Shentun.Peis.Application.Contracts.xml");
  299. options.IncludeXmlComments(commentsFileDro, true);
  300. });
  301. }
  302. public override void OnApplicationInitialization(ApplicationInitializationContext context)
  303. {
  304. var app = context.GetApplicationBuilder();
  305. var env = context.GetEnvironment();
  306. //请求错误提示配置
  307. app.UseErrorHandling();
  308. if (env.IsDevelopment())
  309. {
  310. app.UseDeveloperExceptionPage();
  311. }
  312. app.UseAbpRequestLocalization();
  313. if (!env.IsDevelopment())
  314. {
  315. app.UseErrorPage();
  316. }
  317. app.UseCorrelationId();
  318. //var staticFile = new StaticFileOptions();
  319. //var filePath = env.ContentRootPath+"UpLoad\\";
  320. ////var filePath = env.ContentRootPath ;
  321. //staticFile.FileProvider = new PhysicalFileProvider(filePath);
  322. //app.UseStaticFiles(new StaticFileOptions
  323. //{
  324. // FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "UpLoad")),
  325. // RequestPath="/UpLoad"
  326. //});
  327. app.UseStaticFiles();
  328. app.UseStaticFiles(new StaticFileOptions
  329. {
  330. FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "UpLoad")),
  331. RequestPath = "/UpLoad"
  332. });
  333. app.UseRouting();
  334. app.UseCors();
  335. app.UseAuthentication();
  336. app.UseAbpOpenIddictValidation();
  337. if (MultiTenancyConsts.IsEnabled)
  338. {
  339. app.UseMultiTenancy();
  340. }
  341. app.UseUnitOfWork();
  342. app.UseAuthorization();
  343. //app.UseMiddleware(typeof(AuthorizationMiddlewareResultHandler));
  344. app.UseSwagger();
  345. app.UseAbpSwaggerUI(c =>
  346. {
  347. //c.SwaggerEndpoint("/swagger/v1/swagger.json", "Peis API");
  348. c.SwaggerEndpoint($"/swagger/Work/swagger.json", "业务API"); //分组显示
  349. c.SwaggerEndpoint($"/swagger/Sys/swagger.json", "底层API"); //分组显示
  350. //c.RoutePrefix = string.Empty; // url 中不显示swagger
  351. var configuration = context.ServiceProvider.GetRequiredService<IConfiguration>();
  352. c.OAuthClientId(configuration["AuthServer:SwaggerClientId"]);
  353. c.OAuthScopes("Peis");
  354. c.DefaultModelExpandDepth(-1);
  355. });
  356. app.UseAuditing();
  357. app.UseAbpSerilogEnrichers();
  358. app.UseConfiguredEndpoints();
  359. }
  360. }