Startup.cs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. using FMSAdmin.Data;
  2. using FMSAdmin.Helpers;
  3. using Microsoft.AspNetCore.Builder;
  4. using Microsoft.AspNetCore.Hosting;
  5. using Microsoft.EntityFrameworkCore;
  6. using Microsoft.Extensions.Configuration;
  7. using Microsoft.Extensions.DependencyInjection;
  8. using Microsoft.Extensions.Hosting;
  9. using Microsoft.Extensions.Logging;
  10. using FMSAdmin.Services;
  11. using System.Linq;
  12. using Microsoft.Extensions.WebEncoders;
  13. using System.Text.Encodings.Web;
  14. using System.Text.Unicode;
  15. using Microsoft.AspNetCore.Authentication.JwtBearer;
  16. using Microsoft.IdentityModel.Tokens;
  17. using System.Text;
  18. using Microsoft.AspNetCore.Mvc;
  19. using System.Text.Json;
  20. using Microsoft.AspNetCore.Http;
  21. using System.Reflection;
  22. using Newtonsoft.Json;
  23. using Newtonsoft.Json.Serialization;
  24. using Quartz.Impl;
  25. using Quartz;
  26. using Quartz.Logging;
  27. using System;
  28. using Microsoft.AspNetCore.StaticFiles;
  29. using GrapeCity.ActiveReports.Aspnetcore.Viewer;
  30. using System.IO;
  31. namespace FMSAdmin {
  32. public class Startup {
  33. public Startup(IConfiguration configuration, IWebHostEnvironment env) {
  34. Environment = env;
  35. Configuration = configuration;
  36. }
  37. public IConfiguration Configuration { get; }
  38. public IWebHostEnvironment Environment { get; }
  39. // This method gets called by the runtime. Use this method to add services to the container.
  40. public void ConfigureServices(IServiceCollection services) {
  41. services.Configure<WebEncoderOptions>(options => {
  42. options.TextEncoderSettings = new TextEncoderSettings(UnicodeRanges.All); // 한글이 인코딩되는 문제 해결
  43. });
  44. services.Configure<ApiBehaviorOptions>(options => {
  45. options.SuppressModelStateInvalidFilter = true;
  46. });
  47. // CORS처리
  48. services.AddCors(options => {
  49. options.AddDefaultPolicy(
  50. builder => builder
  51. .AllowAnyOrigin()
  52. .AllowAnyMethod()
  53. .AllowAnyHeader()
  54. );
  55. });
  56. // 서비스들 추가
  57. foreach (var type in Assembly.GetExecutingAssembly().GetTypes().Where(x => x.Namespace == "FMSAdmin.Services")) {
  58. services.AddScoped(type);
  59. }
  60. foreach (var type in Assembly.GetExecutingAssembly().GetTypes().Where(x => x.Namespace == "FMSApp.Services")) {
  61. services.AddScoped(type);
  62. }
  63. // 리파지토리 추가
  64. foreach (var type in Assembly.GetExecutingAssembly().GetTypes().Where(x => x.Namespace == "FMSApp.Repositories")) {
  65. services.AddScoped(type);
  66. }
  67. // 기타 추가
  68. services.AddScoped<StorageHelper>();
  69. services.AddScoped<QrCodeHelper>();
  70. services.AddScoped<PushHelper>();
  71. services.AddControllers(options =>
  72. options.Filters.Add(new HttpResponseExceptionFilter())
  73. )/*.AddJsonOptions(options => { // JSON 카멜케이스 - DictionaryKeyPolicy (ModelState Error)는 반영안됨
  74. options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
  75. options.JsonSerializerOptions.PropertyNamingPolicy = null;
  76. options.JsonSerializerOptions.DictionaryKeyPolicy = null;
  77. });
  78. 기본 JSON모듈대신 Newtonsoft 이용. (파라메터 바인딩시에 int 자동캐스팅이 별도작업없이가능)*/
  79. .AddNewtonsoftJson(options => {
  80. options.SerializerSettings.ContractResolver = new DefaultContractResolver();
  81. options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
  82. //options.SerializerSettings.MaxDepth = 5;
  83. });
  84. if (Environment.IsDevelopment()) {
  85. var sever = Configuration.GetConnectionString("Server");
  86. if (sever != null && sever == "Sqlite") {
  87. services.AddDbContext<FMSContext>(
  88. options => options.UseLazyLoadingProxies().UseSqlite(Configuration.GetConnectionString("SqliteContext")));
  89. } else {
  90. services.AddDbContext<FMSContext>(
  91. options => options.UseLazyLoadingProxies().UseSqlServer(Configuration.GetConnectionString("SqlServerContext")));
  92. }
  93. } else {
  94. // LazyLoading 추가
  95. services.AddDbContext<FMSContext>(
  96. options => options.UseLazyLoadingProxies().UseSqlServer(Configuration.GetConnectionString("SqlServerContext")));
  97. }
  98. // AppSettings 객체로 가져오기
  99. var appSettingsSection = Configuration.GetSection("AppSettings");
  100. services.Configure<AppSettings>(appSettingsSection);
  101. // JWT 시크릿키 설정
  102. var appSettings = appSettingsSection.Get<AppSettings>();
  103. var key = Encoding.ASCII.GetBytes(appSettings.Secret);
  104. // JWT 인증
  105. services.AddAuthentication(x => {
  106. x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
  107. x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
  108. })
  109. .AddJwtBearer(x => {
  110. x.RequireHttpsMetadata = false;
  111. x.SaveToken = true;
  112. x.TokenValidationParameters = new TokenValidationParameters {
  113. ValidateIssuerSigningKey = true,
  114. IssuerSigningKey = new SymmetricSecurityKey(key),
  115. ValidateIssuer = false,
  116. ValidateAudience = false
  117. };
  118. });
  119. // AR 세팅
  120. services.AddReporting();
  121. // Job Scheduler 추가
  122. bool runScheduler = false;
  123. if (appSettings.Scheduler != "off") { // 설정으로 실행 여부 관리
  124. runScheduler = true;
  125. }
  126. if (runScheduler) {
  127. LogProvider.SetCurrentLogProvider(new QuartzLogProvider());
  128. foreach (var type in Assembly.GetExecutingAssembly().GetTypes().Where(x => x.Namespace == "FMSAdmin.QuartzSchedule.Jobs")) {
  129. services.AddScoped(type);
  130. }
  131. foreach (var type in Assembly.GetExecutingAssembly().GetTypes().Where(x => x.Namespace == "FMSAdmin.QuartzSchedule.Schedulers")) {
  132. services.AddScoped(type);
  133. }
  134. services.AddSingleton<QuartzJobRunner>();
  135. services.AddSingleton<QuartzJobFactory>();
  136. services.AddScoped<QuartzSchedule.Startup>();
  137. services.AddScoped<QuartzSchedulerListener>();
  138. var scheduler = StdSchedulerFactory.GetDefaultScheduler().GetAwaiter().GetResult();
  139. services.AddSingleton(scheduler);
  140. services.AddHostedService<QuartzHostedService>();
  141. }
  142. // iis
  143. services.Configure<IISServerOptions>(options => {
  144. options.AutomaticAuthentication = false;
  145. });
  146. }
  147. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  148. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory) {
  149. ApplicationLogging.ConfigureLogger(loggerFactory);
  150. // static 클래스 로거설정
  151. Util._logger = ApplicationLogging.CreateLogger("Util");
  152. EntityHelper._logger = ApplicationLogging.CreateLogger("EntityHelper");
  153. // 기본 익셉션 핸들러 설정
  154. if (env.IsDevelopment()) {
  155. app.UseExceptionHandler("/error-local-development");
  156. } else {
  157. app.UseExceptionHandler("/error");
  158. }
  159. // 추가 static files 설정
  160. var provider = new FileExtensionContentTypeProvider();
  161. provider.Mappings[".dwg"] = "application/acad";
  162. provider.Mappings[".plist"] = "text/xml";
  163. provider.Mappings[".ipa"] = "application/octet-stream";
  164. //app.UseStaticFiles();
  165. app.UseStaticFiles(new StaticFileOptions() {
  166. ContentTypeProvider = provider
  167. });
  168. app.UseRouting();
  169. app.UseCors();
  170. app.UseAuthentication();
  171. app.UseAuthorization();
  172. app.UseEndpoints(endpoints => {
  173. endpoints.MapControllers();
  174. });
  175. // AR 추가
  176. app.UseReporting(settings => {
  177. settings.UseCompression = true;
  178. settings.UseFileStore(new DirectoryInfo("Reports")); // Reports 디렉토리
  179. });
  180. }
  181. }
  182. }