Startup.cs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. using System.IO;
  2. using GxPress.Api.ServiceExtensions;
  3. using GxPress.Common.AppOptions;
  4. using GxPress.Common.Middleware;
  5. using GxPress.Common.Tools;
  6. using Microsoft.AspNetCore.Builder;
  7. using Microsoft.AspNetCore.Hosting;
  8. using Microsoft.AspNetCore.Http;
  9. using Microsoft.AspNetCore.Http.Features;
  10. using Microsoft.AspNetCore.Mvc;
  11. using Microsoft.Extensions.Configuration;
  12. using Microsoft.Extensions.DependencyInjection;
  13. using Microsoft.Extensions.FileProviders;
  14. using Microsoft.Extensions.Hosting;
  15. using Newtonsoft.Json;
  16. using Newtonsoft.Json.Serialization;
  17. using Quartz;
  18. using Quartz.Impl;
  19. namespace GxPress.Api
  20. {
  21. public class Startup
  22. {
  23. public IConfiguration Configuration { get; }
  24. public Startup(IConfiguration configuration)
  25. {
  26. Configuration = configuration;
  27. ConfigHelper.Configs = Configuration;
  28. }
  29. // This method gets called by the runtime. Use this method to add services to the container.
  30. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
  31. public void ConfigureServices(IServiceCollection services)
  32. {
  33. services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
  34. services.AddSingleton<ISchedulerFactory, StdSchedulerFactory>();
  35. services.AddControllers().AddNewtonsoftJson(options =>
  36. {
  37. options.SerializerSettings.ContractResolver = new DefaultContractResolver();
  38. //options.UseCamelCasing(true);
  39. options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
  40. //// 忽略循环引用
  41. //options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
  42. //// 如字段为null值,该字段不会返回到前端
  43. // options.SerializerSettings.NullValueHandling = NullValueHandling.Include;
  44. }).AddJsonOptions(options =>
  45. {
  46. options.JsonSerializerOptions.PropertyNamingPolicy = null;
  47. }).SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
  48. //文件上传限制60MB
  49. services.Configure<FormOptions>(options =>
  50. {
  51. options.MultipartBodyLengthLimit = 60000000;
  52. });
  53. //数据库
  54. var databaseSection = Configuration.GetSection("Database");
  55. var cacheSection = Configuration.GetSection("Cache:ConnectionString");
  56. var storageOptions = Configuration.GetSection("Storage").Get<StorageOptions>();
  57. services.Configure<DatabaseOptions>(databaseSection);
  58. services.AddDistributedCache(cacheSection.Value);
  59. services.AddStorage(storageOptions);
  60. services.Configure<ApiBehaviorOptions>(o =>
  61. {
  62. o.InvalidModelStateResponseFactory = actionContext =>
  63. new BadRequestObjectResult(JsonConvert.SerializeObject(new
  64. {
  65. Message = "参数错误",
  66. StackTrace = JsonConvert.SerializeObject(actionContext.ModelState)
  67. }));
  68. });
  69. // var client = new CSRedisClient(redisSection.Value);
  70. // //初始化 RedisHelper
  71. // RedisHelper.Initialization(client);
  72. // //注册分布式缓存
  73. // var options = Options.Create(new Microsoft.Extensions.Caching.Redis.RedisCacheOptions
  74. // {
  75. // Configuration = redisSection.Value,
  76. // InstanceName = string.Empty,
  77. // });
  78. // services.AddSingleton<IDistributedCache>(new RedisCache(options));
  79. services.AddRepositories();
  80. services.AddServices();
  81. services.AddMappers();
  82. services.AddJwtAuthentication(Configuration);
  83. services.AddCors(options =>
  84. {
  85. options.AddPolicy(
  86. "AllowAny",
  87. x =>
  88. {
  89. x.AllowAnyHeader()
  90. .AllowAnyMethod()
  91. .SetIsOriginAllowed(_ => true)
  92. .AllowCredentials();
  93. });
  94. });
  95. services.AddSwashbuckle();
  96. }
  97. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  98. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  99. {
  100. //var provider = new FileExtensionContentTypeProvider();
  101. // // Add new mappings
  102. // provider.Mappings[".epub"] = "application/octet-stream";
  103. if (env.IsDevelopment())
  104. {
  105. app.UseDeveloperExceptionPage();
  106. }
  107. //最上层的自定义异常处理中间件
  108. app.UseMiddleware<ExceptionMiddleware>();
  109. app.UseRouting();
  110. app.UseJwtAuthorization();
  111. var cachePeriod = env.IsDevelopment() ? "600" : "604800";
  112. app.UseStaticFiles(new StaticFileOptions
  113. {
  114. //ContentTypeProvider = provider,
  115. //非标准类型
  116. ServeUnknownFileTypes = true,
  117. //返回类型
  118. DefaultContentType = "application/octet-stream",
  119. OnPrepareResponse = ctx =>
  120. {
  121. // Requires the following import:
  122. // using Microsoft.AspNetCore.Http;
  123. ctx.Context.Response.Headers.Append("Cache-Control", $"public, max-age={cachePeriod}");
  124. ctx.Context.Response.Headers.Append("Access-Control-Allow-Headers", $"X-Requested-With");
  125. ctx.Context.Response.Headers.Append("Access-Control-Allow-Origin", $"*");
  126. ctx.Context.Response.Headers.Append("Access-Control-Allow-Methods", $"GET,POST,OPTIONS");
  127. ctx.Context.Response.Headers.Append("Connection", $"keep-alive");
  128. }
  129. });
  130. // app.UseStaticFiles(new StaticFileOptions
  131. // {
  132. // FileProvider = new PhysicalFileProvider(
  133. // Path.Combine(Directory.GetCurrentDirectory(), "wwwroot")),
  134. // RequestPath = "",
  135. // ContentTypeProvider = provider
  136. // });
  137. app.UseDirectoryBrowser(new DirectoryBrowserOptions
  138. {
  139. FileProvider = new PhysicalFileProvider(
  140. Path.Combine(Directory.GetCurrentDirectory(), "wwwroot")),
  141. RequestPath = "/MyImages"
  142. });
  143. app.UseCors("AllowAny");
  144. app.UseSwashbuckle();
  145. app.UseEndpoints(endpoints =>
  146. {
  147. endpoints.MapControllers();
  148. endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
  149. });
  150. }
  151. }
  152. }