Startup.cs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. using Host.Filters;
  2. using Host.Managers;
  3. using Host.Services;
  4. using Microsoft.AspNetCore.Builder;
  5. using Microsoft.AspNetCore.Hosting;
  6. using Microsoft.Extensions.Configuration;
  7. using Microsoft.Extensions.DependencyInjection;
  8. using Microsoft.Extensions.PlatformAbstractions;
  9. using Microsoft.OpenApi.Models;
  10. using Serilog;
  11. using Serilog.Events;
  12. using System.Collections.Generic;
  13. using System.IO;
  14. using System.Linq;
  15. namespace Host
  16. {
  17. public class Startup
  18. {
  19. public Startup(IConfiguration configuration)
  20. {
  21. Configuration = configuration;
  22. }
  23. public IConfiguration Configuration { get; }
  24. // This method gets called by the runtime. Use this method to add services to the container.
  25. public void ConfigureServices(IServiceCollection services)
  26. {
  27. // 日志配置
  28. LogConfig();
  29. #region 跨域
  30. services.AddCors(options =>
  31. {
  32. options.AddPolicy("AllowSameDomain", policyBuilder =>
  33. {
  34. policyBuilder
  35. .AllowAnyMethod()
  36. .AllowAnyHeader();
  37. var allowedHosts = Configuration.GetSection("AllowedHosts").Get<List<string>>();
  38. if (allowedHosts?.Any(t => t == "*") ?? false)
  39. policyBuilder.AllowAnyOrigin(); //允许任何来源的主机访问
  40. else if (allowedHosts?.Any() ?? false)
  41. policyBuilder.AllowCredentials().WithOrigins(allowedHosts.ToArray()); //允许类似http://localhost:8080等主机访问
  42. });
  43. });
  44. //services.AddRouting(r => r.SuppressCheckForUnhandledSecurityMetadata = true);
  45. #endregion
  46. //services.AddMvc();
  47. services.AddControllersWithViews(
  48. t =>
  49. {
  50. t.Filters.Add<AuthorizationFilter>();
  51. }).AddNewtonsoftJson();
  52. services.AddHostedService<HostedService>();
  53. services.AddSingleton<SchedulerCenter>();
  54. services.AddSwaggerGen(options =>
  55. {
  56. options.SwaggerDoc("v1", new OpenApiInfo
  57. {
  58. Version = "v1",
  59. Title = "MsSystem API"
  60. });
  61. //Determine base path for the application.
  62. var basePath = PlatformServices.Default.Application.ApplicationBasePath;
  63. //Set the comments path for the swagger json and ui.
  64. var xmlPath = Path.Combine(basePath, "Host.xml");
  65. options.IncludeXmlComments(xmlPath);
  66. });
  67. }
  68. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  69. public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  70. {
  71. if (env.IsDevelopment())
  72. {
  73. app.UseDeveloperExceptionPage();
  74. }
  75. //app.UseMvc();
  76. app.Use(async (context, next) =>
  77. {
  78. await next();
  79. if (context.Response.StatusCode == 404 &&
  80. !Path.HasExtension(context.Request.Path.Value) &&
  81. !context.Request.Path.Value.StartsWith("/api/"))
  82. {
  83. context.Request.Path = "/index.html";
  84. await next();
  85. }
  86. });
  87. //app.UseMvcWithDefaultRoute();
  88. app.UseDefaultFiles();
  89. app.UseStaticFiles();
  90. app.UseSwagger();
  91. app.UseSwaggerUI(c =>
  92. {
  93. c.SwaggerEndpoint("/swagger/v1/swagger.json", "MsSystem API V1");
  94. });
  95. app.UseRouting();
  96. //https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.0
  97. app.UseCors("AllowSameDomain");
  98. app.UseAuthorization();
  99. app.UseEndpoints(endpoints =>
  100. {
  101. endpoints.MapControllers();
  102. });
  103. }
  104. /// <summary>
  105. /// 日志配置
  106. /// </summary>
  107. private void LogConfig()
  108. {
  109. //nuget导入
  110. //Serilog.Extensions.Logging
  111. //Serilog.Sinks.RollingFile
  112. //Serilog.Sinks.Async
  113. var fileSize = 1024 * 1024 * 10;//10M
  114. var fileCount = 2;
  115. Log.Logger = new LoggerConfiguration()
  116. .Enrich.FromLogContext()
  117. .MinimumLevel.Debug()
  118. .MinimumLevel.Override("System", LogEventLevel.Information)
  119. .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
  120. .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Debug).WriteTo.Async(
  121. a =>
  122. {
  123. a.RollingFile("File/logs/log-{Date}-Debug.txt", fileSizeLimitBytes: fileSize, retainedFileCountLimit: fileCount);
  124. }
  125. ))
  126. .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Information).WriteTo.Async(
  127. a =>
  128. {
  129. a.RollingFile("File/logs/log-{Date}-Information.txt", fileSizeLimitBytes: fileSize, retainedFileCountLimit: fileCount);
  130. }
  131. ))
  132. .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Warning).WriteTo.Async(
  133. a =>
  134. {
  135. a.RollingFile("File/logs/log-{Date}-Warning.txt", fileSizeLimitBytes: fileSize, retainedFileCountLimit: fileCount);
  136. }
  137. ))
  138. .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Error).WriteTo.Async(
  139. a =>
  140. {
  141. a.RollingFile("File/logs/log-{Date}-Error.txt", fileSizeLimitBytes: fileSize, retainedFileCountLimit: fileCount);
  142. }
  143. ))
  144. .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Fatal).WriteTo.Async(
  145. a =>
  146. {
  147. a.RollingFile("File/logs/log-{Date}-Fatal.txt", fileSizeLimitBytes: fileSize, retainedFileCountLimit: fileCount);
  148. }
  149. ))
  150. //所有情况
  151. .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => true)).WriteTo.Async(
  152. a =>
  153. {
  154. a.RollingFile("File/logs/log-{Date}-All.txt", fileSizeLimitBytes: fileSize, retainedFileCountLimit: fileCount);
  155. }
  156. )
  157. .CreateLogger();
  158. }
  159. }
  160. }