Startup.cs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. using Autofac;
  2. using Autofac.Extensions.DependencyInjection;
  3. using Microsoft.AspNetCore.Builder;
  4. using Microsoft.AspNetCore.DataProtection;
  5. using Microsoft.AspNetCore.Hosting;
  6. using Microsoft.AspNetCore.Http;
  7. using Microsoft.Extensions.Configuration;
  8. using Microsoft.Extensions.DependencyInjection;
  9. using Microsoft.Extensions.FileProviders;
  10. using Microsoft.Extensions.Hosting;
  11. using Newtonsoft.Json.Serialization;
  12. using System;
  13. using System.IO;
  14. using System.Text;
  15. using System.Text.Encodings.Web;
  16. using System.Text.Unicode;
  17. using YiSha.Admin.Web.AutoFac;
  18. using YiSha.Admin.Web.Controllers;
  19. using YiSha.Data.Repository;
  20. using YiSha.Util;
  21. using YiSha.Util.Model;
  22. namespace YiSha.Admin.Web
  23. {
  24. public class Startup
  25. {
  26. public IConfiguration Configuration { get; }
  27. public IWebHostEnvironment WebHostEnvironment { get; set; }
  28. public Startup(IConfiguration configuration, IWebHostEnvironment env)
  29. {
  30. Configuration = configuration;
  31. WebHostEnvironment = env;
  32. GlobalContext.LogWhenStart(env);
  33. GlobalContext.HostingEnvironment = env;
  34. }
  35. // This method gets called by the runtime. Use this method to add services to the container.
  36. public IServiceProvider ConfigureServices(IServiceCollection services)
  37. {
  38. if (WebHostEnvironment.IsDevelopment())
  39. {
  40. services.AddRazorPages().AddRazorRuntimeCompilation();
  41. }
  42. services.Configure<CookiePolicyOptions>(options =>
  43. {
  44. // This lambda determines whether user consent for non-essential cookies is needed for a given request.
  45. options.CheckConsentNeeded = context => true;
  46. options.MinimumSameSitePolicy = SameSiteMode.None;
  47. });
  48. services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));
  49. services.AddControllersWithViews(options =>
  50. {
  51. options.Filters.Add<GlobalExceptionFilter>();
  52. options.ModelMetadataDetailsProviders.Add(new ModelBindingMetadataProvider());
  53. }).AddNewtonsoftJson(options =>
  54. {
  55. // 返回数据首字母不小写,CamelCasePropertyNamesContractResolver是小写
  56. options.SerializerSettings.ContractResolver = new DefaultContractResolver();
  57. });
  58. services.AddMemoryCache();
  59. services.AddSession();
  60. services.AddHttpContextAccessor();
  61. services.AddOptions();
  62. services.AddDataProtection().PersistKeysToFileSystem(new DirectoryInfo(GlobalContext.HostingEnvironment.ContentRootPath + Path.DirectorySeparatorChar + "DataProtection"));
  63. Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); // 注册Encoding
  64. GlobalContext.SystemConfig = Configuration.GetSection("SystemConfig").Get<SystemConfig>();
  65. GlobalContext.Services = services;
  66. GlobalContext.Configuration = Configuration;
  67. return RegisterAutofac(services);//注册Autofac
  68. }
  69. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  70. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  71. {
  72. if (!string.IsNullOrEmpty(GlobalContext.SystemConfig.VirtualDirectory))
  73. {
  74. app.UsePathBase(new PathString(GlobalContext.SystemConfig.VirtualDirectory)); // 让 Pathbase 中间件成为第一个处理请求的中间件, 才能正确的模拟虚拟路径
  75. }
  76. if (WebHostEnvironment.IsDevelopment())
  77. {
  78. GlobalContext.SystemConfig.Debug = true;
  79. app.UseDeveloperExceptionPage();
  80. }
  81. else
  82. {
  83. app.UseExceptionHandler("/Home/Error");
  84. }
  85. string resource = Path.Combine(env.ContentRootPath, "Resource");
  86. FileHelper.CreateDirectory(resource);
  87. app.UseStaticFiles(new StaticFileOptions
  88. {
  89. OnPrepareResponse = GlobalContext.SetCacheControl
  90. });
  91. app.UseStaticFiles(new StaticFileOptions
  92. {
  93. RequestPath = "/Resource",
  94. FileProvider = new PhysicalFileProvider(resource),
  95. OnPrepareResponse = GlobalContext.SetCacheControl
  96. });
  97. string areas = Path.Combine(env.ContentRootPath, "Areas");
  98. FileHelper.CreateDirectory(areas);
  99. app.UseStaticFiles(new StaticFileOptions
  100. {
  101. OnPrepareResponse = GlobalContext.SetCacheControl
  102. });
  103. app.UseStaticFiles(new StaticFileOptions
  104. {
  105. RequestPath = "/Areas",
  106. FileProvider = new PhysicalFileProvider(areas),
  107. OnPrepareResponse = GlobalContext.SetCacheControl
  108. });
  109. app.UseSession();
  110. app.UseRouting();
  111. app.UseEndpoints(endpoints =>
  112. {
  113. endpoints.MapControllerRoute("areas", "{area:exists}/{controller=Home}/{action=Index}/{id?}");
  114. endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
  115. });
  116. GlobalContext.ServiceProvider = app.ApplicationServices;
  117. }
  118. /// <summary>
  119. /// Autofac容器注入
  120. /// </summary>
  121. /// <param name="services"></param>
  122. /// <returns></returns>
  123. private IServiceProvider RegisterAutofac(IServiceCollection services)
  124. {
  125. services.AddScoped<IRepositoryFactory, RepositoryFactory>();
  126. //实例化Autofac容器
  127. var builder = new ContainerBuilder();
  128. //将Services中的服务填充到Autofac中
  129. builder.Populate(services);
  130. //新模块组件注册
  131. builder.RegisterModule<AutofacModuleRegister>();
  132. //创建容器
  133. var Container = builder.Build();
  134. //第三方IOC接管 core内置DI容器
  135. return new AutofacServiceProvider(Container);
  136. }
  137. }
  138. }